有没有一种方法可以从JQuery Ajax调用返回值(在我的情况下为xml) [英] Is there a way to return a value (xml in my case) from a JQuery Ajax Call
问题描述
我想我缺少一些非常基本的东西,也许有人可以填补我的空白.我从两个地方使用过ajax调用.因此,现在我试图通过使调用返回一个值来重用该调用.看起来像这样:
I guess I am missing something quite fundamental and maybe someone can fill me in. I have used an ajax call from two places. So now I am trying to reuse that call by making the call return a value. It looks something like this:
function getInfo()
{
$.ajax({
type: "GET",
url: "../ajax.aspx?action=getInfo&id=4",
dataType: "xml",
async: false,
error: function() {
alert("Something went wrong.");
},
success: function(xml) {
// Do some extra work here
$(xml).find("room").each(function() {
// Do something based on the xml
});
// Something else can use this XML so return it too.
// Why does this return not work???
return xml;
}
});
}
所以我在脚本的其他地方调用了该函数
So somewhere else in the script i am calling that function
var xml = getInfo();
// Try do something with it now but it says that it is undefined
当我说它是不确定的时,我是在谈论Firebug.
and when i say it says it is undefined I am talking about Firebug.
推荐答案
关闭异步功能并不是一种很好的AJAX编程风格.您将失去这项技术的许多优点. 从jquery文档中:
Turning off the asynchronous functionality is imho not a very good AJAX programming style. You will loose a lot of the advantages of this technology. From the jquery documentation:
请注意,同步请求可能会 暂时锁定浏览器, 禁用任何操作,而 请求处于活动状态.
Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
如果仍然需要这样做: $ .ajax返回它创建的XMLHTTPRequest对象.并且您的getInfo方法也应该返回该值,因此您的代码应按如下所示进行修改:
If you need to do it anyway: $.ajax returns the XMLHTTPRequest object it creates. And your getInfo method should return that as well, so your code should be modified like this:
function getInfo()
{
return $.ajax({
type: "GET",
url: "../ajax.aspx?action=getInfo&id=4",
dataType: "xml",
async: false,
error: function() {
alert("Something went wrong.");
},
success: function(xml) {
// Do some extra work here
$(xml).find("room").each(function() {
// Do something based on the xml
});
// Something else can use this XML so return it too.
// Why does this return not work???
return xml;
}
}).responseText;
}
var xml = getInfo();
这篇关于有没有一种方法可以从JQuery Ajax调用返回值(在我的情况下为xml)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!