如何引入回调函数来返回jquery中的AJAX数据?

时间:2012-11-20 16:44:24

标签: javascript jquery ajax callback

我正在尝试从函数crimeTrendTable返回一些数据,该函数使用jquery .ajax将一些数据从Web中提取到一个名为postcodeConvert的函数。

我认为我需要实现一个回调函数,以确保它只返回数据后返回信息,但我对如何操作有点困惑?有人可以帮忙吗?

$(document).ready(function()
{
function crimeTrendTable(latitude, longitude){
    //Find all available dates
    availability_url = "http://policeapi2.rkh.co.uk/api/crimes-street-dates";
    listings = $.ajax({

        dataType: 'jsonp',
        url: availability_url, 
        success: function(data){
            latest = data[0]['date'];
            three_months_date = data[3]['date'];
            six_months_date = data[6]['date'];
            year_ago_date = data[12]['date'];
            list_dates = [latest, three_months_date, six_months_date, year_ago_date];
        },
        error: function(jqXHR, textStatus, errorThrown){ 
            $('#results').html('<h2>Something went wrong!</h2><p><b>' + textStatus  + '</b> ' + errorThrown  + '</p>');
        }
    })


} 
function postcodeConvert(entry){

    //Convert to upper case
    entry = entry.toUpperCase().replace(" ", "");
    base_url = "http://mapit.mysociety.org/postcode/";
    query_url = base_url+entry;
    console.log(query_url);
    $.getJSON(query_url, function(data){
        $('div#results').html("<p>Latitude: "+data['wgs84_lat']+"</p><p>Longitude: "+data['wgs84_lon'])+"</p>";
        data_results = "";
        data_results = crimeTrendTable(data['wgs84_lat'], data['wgs84_lon']);
        console.log("postcode"+data_results);
        return data_results;
    })

}    

$('#postcode').focus(); //ensure the place field is the first box highlighted
      //Disable the submit button from sending anything as we don't need to...
$('#form_submit').submit(function(){
  return false;
});//end submit function
$(':submit').click(function(){
    //function convert text box postcode into lat long
 if ($('#postcode').val() !=''){
    entry = $('#postcode').val();
    postcodeConvert(entry);           
 }  
}); 

});

3 个答案:

答案 0 :(得分:2)

当从服务器返回数据时(http状态为200)

,将运行此方法/函数
function(data){
        latest = data[0]['date'];
        three_months_date = data[3]['date'];
        six_months_date = data[6]['date'];
        year_ago_date = data[12]['date'];
        list_dates = [latest, three_months_date, six_months_date, year_ago_date];
    }

如果您在该函数中添加对方法的调用,它将在您拥有数据时运行。否则,你可以在“success:”中编写一个方法名称,如果你更容易拥有像这样的sepparate函数:

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

$.ajax({

    dataType: 'jsonp',
    url: availability_url, 
    success: callback,
    error: function(jqXHR, textStatus, errorThrown){ 
        $('#results').html('<h2>Something went wrong!</h2><p><b>' + textStatus  + '</b> ' + errorThrown  + '</p>');
    }
});

答案 1 :(得分:0)

您是正确的,需要回调来获取postcodeConvert函数的数据结果。

你现在的回报

return data_results;

不会真的做任何事情。如果修改postcodeConvert函数定义以使其接受回调参数

function postcodeConvert(entry, callback) {

并将您的return语句更改为回调调用

callback(data_results)

然后您可以像这样调用postcodeConvert函数:

postcodeConvert(entry, function(data_results) {
// use data_results
});

答案 2 :(得分:0)

如果返回ajax XHR对象,则可以使用内置的done()回调来确保数据可用:

$(document).ready(function() {
function crimeTrendTable(latitude, longitude){
    return $.ajax({
        dataType: 'jsonp',
        url: availability_url, 
        error: function(jqXHR, textStatus, errorThrown){ 
            //error function does'nt work with JSONP, remove this
        }
    }):
}

function postcodeConvert(entry){
    /* more stuff here */
    return $.getJSON(query_url, function(data){
        $('div#results').html("<p>Latitude: "+data['wgs84_lat']+"</p><p>Longitude: "+data['wgs84_lon'])+"</p>";
        return crimeTrendTable(data['wgs84_lat'], data['wgs84_lon']);
    }):
}    

$('input[type="submit"]').click(function(e){
    e.preventDefault();
    if ($('#postcode').val() !=''){
       entry = $('#postcode').val();
       postcodeConvert(entry).done(function(data) {
          //data is now avaiable here
          latest = data[0]['date'];
          three_months_date = data[3]['date'];
          six_months_date = data[6]['date'];
       });
    }  
}); 

请注意,您的代码中存在一些错误,例如您的所有变量都是全局的?