2014-06-08 101 views
0

我正在做一些地理定位/地图工作,并建立一个JQuery小部件,以便代码是很好的和可移植的未来项目。JQuery UI小部件与AJAX请求

尽管发出AJAX请求,但我已经跑到了墙上;这里有一对夫妇从我的插件的方法:

getGeocodeForAddress: function(address) {  
    req = this._googleMapsApiRequest('geocode','json','address='+address); 

    //We need 'req' to be the response from the API request so we can do work with it. 

}, 


/** 
* Private Maps API request method. This will help to construct a call to Google Maps API. 
* 
* @param service 
* @param output 
* @param params 
*/ 
_googleMapsApiRequest: function(service,output,params) { 

    var widget = this; 
    var protocol = (this.options.useHttps) ? 'https://' : 'http://'; 

    if (this.options.googleMapsApiKey != '') { 
     params += '&key' + this.options.googleMapsApiKey; 
    }   

    var uri = protocol + 'maps.googleapis.com/maps/api/' + service + '/' + output + '?' + params; 
    this._sendToLog("Google Maps API Request: " + uri); 

    $.ajax({ 
     async: false, 
     type: "GET", 
     cache: false, 
     url: encodeURI(uri), 
     success: function(response) {     
      //We need the contents of response to be available to the method that called this one. 
     }, 
     error: function() { 
      widget._sendToLog('AJAX error'); 
     },    
    }); 


}, 

的具体问题是,一旦Ajax请求作出,并返回它的成功,我不能得到的数据返回到调用它的方法。

我试着在_googleMapsApiRequest中使用widget.options.ajaxResponse设置一个内部选项,但似乎只在调用方法中为'null',我尝试从AJAX方法内部返回响应,但是这并没有'不管工作。

我确定我需要在_googleMapsApiRequest方法中进行回调,以便它会等待该方法完成,然后我可以基于该方法执行代码,但是如何在小部件中执行该操作?

回答

0

休息一下思考别的事情,然后再多研究一下,我想出了一个回调解决方案......它看起来有点笨重,但它似乎也有诀窍,任何人都可以改进它?

getGeocodeForAddress: function(address) {  

    this._googleMapsApiRequest('geocode','json','address='+address, function(response) 
    {   
     //I can access response within this callback. 
    }); 

}, 


/** 
* Private Maps API request method. This will help to construct a call to Google Maps API. 
* 
* @param service 
* @param output 
* @param params 
*/ 
_googleMapsApiRequest: function(service, output, params, callback) { 

    var widget = this; 
    var protocol = (this.options.useHttps) ? 'https://' : 'http://'; 

    if (this.options.googleMapsApiKey != '') { 
     params += '&key' + this.options.googleMapsApiKey; 
    }   

    var uri = protocol + 'maps.googleapis.com/maps/api/' + service + '/' + output + '?' + params; 
    this._sendToLog("Google Maps API Request: " + uri); 

    $.ajax({ 
     async: false, 
     type: "GET", 
     cache: false, 
     url: encodeURI(uri), 
     success: function(response) {     
      widget._sendToLog('AJAX success, response follows'); 
      widget._sendToLog(response); 
     }, 
     error: function() { 
      widget._sendToLog('AJAX error'); 
     }    
    }).done(function(response) { 
     if (typeof callback == "function") { 
      callback(response); 
     } 
    }); 
}, 

我没有测试过,看看如何处理不成功的Ajax请求,但它至少在申请工作的伎俩。