jQuery 返回值未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13848123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery Return value undefined
提问by Bob Jones
FIXED! THANKS! See "Corrected Code" below.
固定的!谢谢!请参阅下面的“更正后的代码”。
The goal is to get data back from the dialog box. I have seen lots of articles, but could not get any of them to work, so I decided to use a web service to pass the data back and forth between the dialog box and the underlying page.
目标是从对话框中取回数据。我看过很多文章,但无法让其中任何一篇文章起作用,因此我决定使用 Web 服务在对话框和底层页面之间来回传递数据。
All of the code is in place except the code that reads values coming back from the web service. I can see in the debugger that the data is being passed back, but when I return to the caller, the returned data is undefined.
除了读取从 Web 服务返回的值的代码之外,所有代码都已就位。我可以在调试器中看到数据正在被传回,但是当我返回到调用者时,返回的数据是未定义的。
jQuery function getLocal calls AJAX, gets good data back, but when it returns to the function that calls it (verbListShow), the returned value is "undefined".
jQuery 函数 getLocal 调用 AJAX,获取好的数据,但是当它返回到调用它的函数(verbListShow)时,返回值是“未定义”。
This is all happening in an ASP.NET page that is written largely in jQuery, and opens a jQuery dialog box.
这一切都发生在一个主要用 jQuery 编写的 ASP.NET 页面中,并打开一个 jQuery 对话框。
function getLocal(name) {
$.ajax({
type: "POST",
async: false,
url: "WebServices/FLSAService.asmx/GetLocalVariable",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ name: name }),
success: function (data) {
var rtn = data.d;
return rtn;
}
});
}
The above code works, but when called, rtn is undefined. Here is the caller:
上面的代码有效,但在调用时,rtn 未定义。这是调用者:
function verbListShow(dutyNumber) {
$('#dlgDutyList').dialog({
modal: true,
show: "slide",
width: 250,
height: 250,
open: function (event, ui) {
setLocal("DUTYNUMBER", dutyNumber);
},
buttons: {
"Select": function () {
var id = getLocal("VERBID"); // <*** Returns undefined
var verb = getLocal("VERB"); // <*** Returns undefined
$.ajax({
type: "POST",
async: false,
url: "WebServices/FLSAService.asmx/SetDuty",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ dutyNum: dutyNumber, id: id, verb: verb }),
success: function (data) {
data = $.parseJSON(data.d);
if (data.ErrorFound) {
showMessage(data.ErrorMessage, 2, true);
}
else {
log('Set Duty: ' + data.StringReturn + ' (' + data.intReturn + ')');
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("updateDuty: "
+ XMLHttpRequest.responseText);
}
});
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
$('#dlgDutyList').dialog('open');
FIXED CODE:
固定代码:
function getLocal(name) {
var rtn = "";
$.ajax({
type: "POST",
async: false,
url: "WebServices/FLSAService.asmx/GetLocalVariable",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ name: name }),
success: function (data) {
rtn = data.d;
}
});
return rtn;
}
回答by Gabriele Petrioli
It defeats the purpose of AJAX to use it synchronously (AJAX stands for Asynchronous Javascript And Xml).
它违背了 AJAX 同步使用它的目的(AJAX 代表 Asynchronous Javascript And Xml)。
Now you cannot return
a value from the success method, but you can store it in a variable and then return that
现在您不能return
从成功方法中获取值,但您可以将其存储在一个变量中,然后返回该值
function getLocal(name) {
var returnValue;
$.ajax({
type: "POST",
async: false,
url: "WebServices/FLSAService.asmx/GetLocalVariable",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ name: name }),
success: function (data) {
returnValue = data.d;
}
});
return returnValue;
}
But the properway would be to use a deferred object
但正确的方法是使用延迟对象
function getLocal(name, resultset) {
return $.ajax({
type: "POST",
url: "WebServices/FLSAService.asmx/GetLocalVariable",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ name: name }),
success: function (data) {
resultset[name] = data.d;
}
});
}
and call it
并称之为
"Select": function() {
var results = {};
var self = this;
$.when(getLocal("VERBID", results), getLocal("VERB", results)).then(function(){
$.ajax({
type: "POST",
url: "WebServices/FLSAService.asmx/SetDuty",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
dutyNum: dutyNumber,
id: results.VERBID,
verb: results.VERB
}),
success: function(data) {
data = $.parseJSON(data.d);
if (data.ErrorFound) {
showMessage(data.ErrorMessage, 2, true);
}
else {
log('Set Duty: ' + data.StringReturn + ' (' + data.intReturn + ')');
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("updateDuty: " + XMLHttpRequest.responseText);
}
});
}).always(function(){
$(self).dialog("close");
});
}
回答by Wojciech D?ubacz
Everything is because $.ajax function don't return any value because of it's asynchronous behaviour, my advice is to make second parameter for getLocal
method called "callback".
一切都是因为 $.ajax 函数不返回任何值,因为它是异步行为,我的建议是为getLocal
称为“回调”的方法设置第二个参数。
Proper way is to do it like so:
正确的方法是这样做:
function getLocal(name, callback) {
$.ajax({
type: "POST",
async: false,
url: "WebServices/FLSAService.asmx/GetLocalVariable",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ name: name }),
success: function (data) {
var rtn = data.d;
callback(rtn);
}
});
}
Then, your main code have to look like that (asynchronous code):
然后,您的主要代码必须如下所示(异步代码):
//some code here
buttons: {
"Select": function () {
getLocal("VERBID", function(id) {
getLocal("VERB", function(verb) {
$.ajax({
type: "POST",
async: false,
url: "WebServices/FLSAService.asmx/SetDuty",
dataType: 'json',
//some code here
});
});
//some code here
To improve this code, to make two asynchronous calls at once, you can use jQuery Deferredobject, and run .resolve(data)
on it just after all ajax calls obtained proper response.
为了改进这段代码,同时进行两个异步调用,您可以使用jQuery Deferred对象,并.resolve(data)
在所有 ajax 调用获得正确响应后运行它。