gal*_*ien 1 javascript ajax jquery json
我正在使用 jQuery。我有一个从名为“get_cats”的远程服务器获取数据的函数。我称它为用返回的值填充数组。当 AJAX 完成时,我想返回这些值。但它不起作用,返回的值未定义。这是非常基本的,但我看不出它在哪里失败。有没有人有线索?
$(function () {
var url = "http://someurl.com/service/";
var cats = [];
cats = get_cats(url);
function get_cats(url) {
var categories = [];
$.getJSON(url + "cats", function (data) {
$.each(data, function (i) {
categories.push(data[i].name);
});
return categories;
});
}
$(document).ajaxStop(function () {
console.log(cats); // fails and returns undefined :'(
});
});
Run Code Online (Sandbox Code Playgroud)
哦,没有 AJAX 是异步的,你不能从中返回任何东西。您应该只在成功回调中使用 AJAX 请求的结果:
$(function () {
var url = "http://someurl.com/service/";
get_cats(url);
function get_cats(url) {
var categories = [];
$.getJSON(url + "cats", function (data) {
$.each(data, function (i) {
categories.push(data[i].name);
});
// Only here you can consume the results of the AJAX request
// Do not attempt to return them, it doesn't make any sense
console.log(categories);
});
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11079 次 |
| 最近记录: |