2

我需要帮助从 jquery ajax 调用中获得回报。

这是我得到的:

var condition = dbCall(km_point['jb'], km_point['kb']);//lat,lng
console.log(condition);

console.log 打印“未定义”

这是 dbCall 函数:

function dbCall(lat, lng){
    $.ajax({
    type: "GET",
    url: 'http://localhost:81/myproject/proxy.php',
    data: { url: lat + ',' + lng, units: "auto" }
    }).done(function( data ) {
        if(data != '' && (data)) {
            var dataJSON = JSON.parse(data);
            //console.log(dataJSON);
            return dataJSON;
        } else {
            return false;
        }
    });
 }

如何获得返回到我的调用函数?

4

2 回答 2

3

It's asynchronous, so you have to wait for the result, only way around that is synchronous ajax, which is not something you should be using.
Change the code to use the result in the done() callback :

function dbCall(lat, lng){
    return $.ajax({
        type: "GET",
        url: 'http://localhost:81/myproject/proxy.php',
        data: { url: lat + ',' + lng, units: "auto" },
        dataType: 'json'
    });
}

dbCall(km_point['jb'], km_point['kb']).done(function(condition) {
    console.log(condition);
});
于 2013-06-28T17:20:53.813 回答
2

AJAX requests are asynchronous, which means you cannot get a return from the response of the AJAX call inside a single function. The better way to do this is to use a callback function that gets called once the AJAX request is finished:

function dbCall(lat, lng, callback){
  $.ajax({
    type: "GET",
    url: 'http://localhost:81/myproject/proxy.php',
    data: { url: lat + ',' + lng, units: "auto" },
    dataType: 'json'
   }).done(function(data){
       callback(data); // execute callback function and pass data
  });
}
于 2013-06-28T17:21:10.227 回答