2014-06-08 67 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請求,但它至少在申請工作的伎倆。