【发布时间】: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