有没有一种方法可以从jQueryAjax调用返回值(在我的例子中是xml)

有没有一种方法可以从jQueryAjax调用返回值(在我的例子中是xml),jquery,ajax,Jquery,Ajax,我想我错过了一些非常基本的东西,也许有人可以告诉我。我使用了来自两个地方的ajax调用。所以现在我试图通过使调用返回一个值来重用该调用。它看起来像这样: function getInfo() { $.ajax({ type: "GET", url: "../ajax.aspx?action=getInfo&id=4", dataType: "xml", async: false, error: function() {

我想我错过了一些非常基本的东西,也许有人可以告诉我。我使用了来自两个地方的ajax调用。所以现在我试图通过使调用返回一个值来重用该调用。它看起来像这样:

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;
    } 
});
}
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();
所以在脚本的其他地方我调用了这个函数

var xml = getInfo();
// Try do something with it now but it says that it is undefined

当我说它是未定义的时,我说的是Firebug。

关闭异步功能不是一种很好的AJAX编程风格。你将失去这项技术的许多优点。 从jquery文档中:

请注意,同步请求可能会 暂时锁定浏览器, 在运行时禁用任何操作 请求处于活动状态

如果您仍然需要这样做: $.ajax返回它创建的XMLHTTPRequest对象。您的getInfo方法也应该返回该值,因此您的代码应该修改如下:

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;
    } 
});
}
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();

是的,async false不是一个好主意。这是我在玩各种选择时意外留下的。它现在被移除了。谢谢:嗯,我担心,如果您打开异步模式,您可能无法在函数调用之后立即返回响应文本,而是使用回调。