2012-06-05 46 views
0

http://pastebin.com/x5UnA1sE需要操作全局變量,但不能在Ajax中操作。需要一種解決此問題的方法

這裏有一點我的困擾編碼的粘貼。

我想操縱jQuery.get回調函數內的全局變量「數據」,以便格式化數據並將其返回到需要的位置。

但是,這個全局變量在回調函數中完全沒有被操縱,這很可能是由於Ajax是異步的。

如何從數據庫獲取我需要的信息並最終將其返回到變量中,因爲我正在試圖在此代碼中執行此操作?

任何方向將不勝感激!

感謝

+0

何時調用mapPoints()函數? – c0deNinja

+0

哪裏是失敗的數據=? – Fresheyeball

回答

1

我認爲你錯過了點asynchroneuscallback 你知道的話,但你不知道如何處理這些行爲。

asynchroneus意味着你必須使用回調 - »意味着你的代碼必須是有效的,你不要把它放在其他東西之後。你有函數,所有這些函數都會做一件事情,並且在他們完成任務時調用指定的回調來完成它們的意圖。

你要做的是不要期望從你的mapPoints返回,但當你完成操作你的數據時調用callback函數。

只需使用回調

function displayPoint(data) { 
    //display all the points 
} 

function callServer(callback { 
    ajaxCall(url, function(data) { dataHandler(data, callback); }); 
} 

function dataHandler(data, callback) { 
    // modify data 

    callback(data); 
} 


// process 
callServer(displayPoint); 

/*** 
call callServer by passing displayPoint as callback 
callServer will perform the ajax call. 
The result will be handle by the anonymus function. 
This function just call the dataHandler function, passing it the datas from the server, and the callback function given to callServer (so displayPoint) 
dataHandler will modify the datas, then call the callback function, passing it the datas. 

YOU DON'T NEED GLOBAL VAR ANYMORE, and that is a really good thing 
***/ 
0

如果你訪問callback函數內部的數據變量?

function mapPoints() 
{ 
    var url = '../common/ajax/get_map_points.php'; 
    var map = {}; 
    $.get(url, map, recieve_map_points,function(data){ 
      console.log(data);   
      return data; 
    });  
} 
0

這將是更好,如果你做這樣的事情

function mapPoints() { 
    var url = '../common/ajax/get_map_points.php'; 
     map = {}; 

    $.get(url, map, recieve_map_points,function(data){ 
     getMyData(data); // call function when you receive data 
    });  
} 

function getMyData(data) { 
    // make something with data 
} 
0

的一個小例子我會更詳細地說明一點什麼Shyju說。

首先,是否ajax是異步的不是問題。您始終可以通過使用asynch: false並具有同步請求來禁用它。

這裏的問題是你如何訪問和操縱返回到服務器的數據。這是關鍵部分。

讓我們打破地方進行更改

$.get(url, map, receive_map_points){}); 

在上面的回調必須與函數聲明進行訪問,沒人能取代這個聲明與你爲你自己做的另一個功能,相反,你可以命名對象,並將其傳遞給另一個函數,以便將數據保存在對象內部。這裏的關鍵是我們需要確保我們send the object back as a JSON encoded array

jQuery.get(url, map, function(data){ 
    //access the data as a json object, extract what we need 
    var ddoc = data.doc; 
    var dtextrank = data.textrank; 

    //pass the newly created data to our function, and have the function extract what it needs. 
    receive_map_points(ddoc, dtextrank); 
}); 

function receive_map_points(doc, textrank){ 
    //same code you used originally. 
} 

正如你可以在上面看到的,我們不需要改變在receive_map_points功能的任何代碼,但我們確實需要改變data being sent back to the function as a JSON encoded array,例如PHP遵循:

json_encode(array("doc" => "something", "textrank" => "something else")); 

希望這有助於。