Javascript Can';无法从jQuery Ajax调用中获得正确的返回值
这应该返回一个包含图片文件名列表的JSON对象。注释的警报显示正确的数据,但Javascript Can';无法从jQuery Ajax调用中获得正确的返回值,javascript,jquery,ajax,return,Javascript,Jquery,Ajax,Return,这应该返回一个包含图片文件名列表的JSON对象。注释的警报显示正确的数据,但警报(getPicsInFolder(“testfolder”)显示“错误” 我做错了什么?您正在异步获取数据。回调函数function(data){}在getPicsInFolder返回后调用 您有两个选择: (坏选项):将ajax调用设置为同步 (正确的选项):重新构造代码,以便在回调中发生任何需要返回数据的操作 一种方法是将回调传递到getPicsInFolder,如下所示: function getPicsInF
警报(getPicsInFolder(“testfolder”)代码>显示“错误”
我做错了什么?您正在异步获取数据。回调函数function(data){}
在getPicsInFolder
返回后调用
您有两个选择:
(坏选项):将ajax调用设置为同步
(正确的选项):重新构造代码,以便在回调中发生任何需要返回数据的操作
一种方法是将回调传递到getPicsInFolder
,如下所示:
function getPicsInFolder(folder, callback) {
return_data = "error";
$.get("getpics.php?folder=" + folder, function (data) {
data = jQuery.parseJSON(data);
$.each(data, function (index, value) {
data[index] = "folders/" + folder + "/" + value;
});
callback(data); //pass data into the callback function
});
然后,在调用getPicsInFolder时,不要执行以下操作:
pics = getPicsInFolder('foldername');
//do something with pics
这样做:
getPicsInFolder('foldername', function (pics) {
//do something with pics
});
您正在调用异步方法,在getPicsInFolder()
函数返回后将调用其回调函数。按照以下示例中的注释进行操作:
function getPicsInFolder(folder) {
return_data = "error";
// Since the $.get() method is using the asynchronous XMLHttpRequest, it
// will not block execution, and will return immediately after it is called,
// without waiting for the server to respond.
$.get("getpics.php", function (data) {
// The code here will be executed only when the server returns
// a response to the "getpics.php" request. This may happen several
// milliseconds after $.get() is called.
return_data = data;
});
// This part will be reached before the server responds to the asynchronous
// request above. Therefore the getPicsInFolder() function returns "error".
return return_data;
}
<>你应该考虑重构你的代码,这样处理JSON对象的逻辑在<代码> $.GET()/<代码>回调中。例如:
$.get("getpics.php?folder=test", function (data) {
// Handle your JSON data in here, or call a helper function that
// can handle it:
handleMyJSON(data); // your helper function
});
您对AJAX的工作原理感到困惑。在函数返回后,请求完成后,数据才可用。而且数据只在回调中可用。AJAX请求应该是异步的(您可以执行同步请求,但代价是停止执行并实际上阻塞您的UI)
getPicsInFolder()
在AJAX请求完成之前返回。您需要更新UI/处理在完成事件时返回的JSON对象(作为参数传递给$.get()
)的匿名函数):
假设我想更新UI中的一个元素
$("#ID-of-a-button-in-the-UI").click(function () // executes on click
{
$.get("url-to-JSON-object", function (json) // executes on request complete
{
$("#ID-of-element-to-update").html(json.rows[0].key); // updates UI
});
});
您可以请求XHR是同步的。@陌生人:是的,您可以,但根据定义,同步XHR不能是AJAX,因为AJAX中的A表示异步:)谢谢。显然,我需要重新思考和改写这一点。
$.get("", function ()
{
// This anonymous function will execute once the request has been completed
// Update your UI/handle your data here
});
$("#ID-of-a-button-in-the-UI").click(function () // executes on click
{
$.get("url-to-JSON-object", function (json) // executes on request complete
{
$("#ID-of-element-to-update").html(json.rows[0].key); // updates UI
});
});