【问题标题】:How to introduce callback function to return AJAX data in jQuery?如何在jQuery中引入回调函数来返回AJAX数据?
【发布时间】:2012-11-20 16:44:24
【问题描述】:

我正在尝试从函数 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);           
 }  
}); 

});

【问题讨论】:

  • 您应该对您的问题/问题进行原型设计。这里有与您的问题无关的代码,这只是对可能帮助您的人的噪音。
  • 难道crimeTendTable中的$.ajax的成功函数中只需要return list_dates;吗?
  • 您好,请将完整示例(带有 HTML)发送至jsfiddle.net。这样可以更轻松地查看错误并为您提供帮助。
  • @Batman 没办法! $.ajax() 是异步的,因此返回最终会“无中生有”。这甚至可能是问题的解决方案:继续在 $.ajax() 的回调中使用 list_dates!
  • @devnull69,我很想这样做,但我想学习如何返回数据以便我可以分解流程。回调似乎是要走的路。

标签: javascript jquery ajax callback


【解决方案1】:

从服务器返回数据时会运行此方法/函数(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];
    }

如果您在该函数中添加对该方法的调用,它将在您获得数据时运行。否则,您可以在“成功:”中写一个方法名称,如果您更容易拥有一个单独的功能,例如:

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>');
    }
});

【讨论】:

    【解决方案2】:

    你说得对,你需要一个回调来从 postcodeConvert 函数中获取数据结果。

    你现在的回报

    return data_results;
    

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

    function postcodeConvert(entry, callback) {
    

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

    callback(data_results)
    

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

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

    【讨论】:

      【解决方案3】:

      如果您返回 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'];
             });
          }  
      }); 
      

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

      【讨论】:

      • 谢谢。我是一名记者,不是开发人员,所以对代码有点草率。
      猜你喜欢
      • 2013-03-31
      • 1970-01-01
      • 2021-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多