簡體   English   中英

如何從ajax成功函數返回數據?

[英]How to return data from ajax success function?

在我的前端 JavaScript 應用程序中,我發出一個 ajax 請求以從服務器獲取數據。 我一拿到數據,就想把那條信息返回給視圖。

var view_data;
$.ajax({
    url:"/getDataFromServer.json",
    //async: false,
    type: "POST",
    dataType: "json",
    success:function(response_data_json) {
        view_data = response_data_json.view_data;
        console.log(view_data); //Shows the correct piece of information
        return view_data; // Does not work. Returns empty data
    }
 });

 // return view_data; --> Keeping the return outside of the ajax call works but then I need to make my ajax call synchronous in order for this return clause to be executed after the ajax call fetches data.

我該怎么做?

而不是從success返回data :將data傳遞給函數。

var view_data;
$.ajax({
    url:"/getDataFromServer.json",
    //async: false,
    type: "POST",
    dataType: "json",
    success:function(response_data_json) {
        view_data = response_data_json.view_data;
        console.log(view_data); //Shows the correct piece of information
        doWork(view_data); // Pass data to a function
    }
 });

function doWork(data)
{
    //perform work here
}

ajax 本質上是 asyc。 代碼不會等待success回調的響應,因此除非通過,否則無法在success之外訪問數據。

您需要處理成功中的數據,請嘗試調用單獨的方法/函數:

function handleResponse(data) {
    // do something with data
}

success:function(response_data_json) {
    handleResponse(response_data_json.view_data); 
}

這是關於 jquery 的ajax 方法的文檔

您也可以只使用外部成功函數而不是 annon 內聯函數,然后無論如何調用該函數。 它仍然會將數據作為參數傳遞

function handleResponse(data) {
  // do something
}

$.ajax({
    url:"/getDataFromServer.json",
    //async: false,
    type: "GET",
    dataType: "json",
    success:handleResponse
 });

更新:正如評論中所指出的,您最好使用http get請求而不是post 它們都有優點,但是可以緩存get請求,因此對於檢索數據,它可能會提高性能。

這是傳遞嬰兒車並獲得回應的最佳方式

function get_table_data_helper(table, id){
    return $.ajax({
        url: DOCUMENT_ROOT + '/php/get_table_data.php',
        type: 'post',
        data: {table: table, id: id},
        async: false,
        success:function(add_clint_res){
            (jQuery.parseJSON(add_clint_res));
        }
    });
}
function get_table_data(table, id, column){
    return jQuery.parseJSON(get_table_data_helper(table, id).success(function (data) {  return jQuery.parseJSON(data);  })['responseText'])[column];

}

然后確實讓你的數據像

get_table_data('city_table', '3', 'city_col')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM