jQuery ajax 成功匿名函数作用域

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1457690/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:30:07  来源:igfitidea点击:

jQuery ajax success anonymous function scope

jqueryajax

提问by Shaun F

How do I update the returnHtml variable from within the anonymous success function?

如何从匿名成功函数中更新 returnHtml 变量?

function getPrice(productId, storeId) {
    var returnHtml = '';

    jQuery.ajax({
        url: "/includes/unit.jsp?" + params,
        cache: false,
        dataType: "html",
        success: function(html){
            returnHtml = html;
        }
    });

    return returnHtml;
}

回答by cletus

That is the wrong approach. The first A in AJAX is Asynchronous. That function returns before the AJAX call returns (or at least it can). So this is not an issue of scope. It is an issue of ordering. There are only two options:

那是错误的做法。AJAX 中的第一个 A 是异步的。该函数在 AJAX 调用返回之前返回(或者至少可以)。所以这不是范围问题。是排序问题。只有两种选择:

  1. Make the AJAX call synchronous (not recommended) with the async: falseoption; or
  2. Change your way of thinking. Instead of returning HTML from the function you need to pass a callback to be called when the AJAX call succeeds.
  1. 使用选项使 AJAX 调用同步(不推荐async: false;或者
  2. 改变你的思维方式。您需要传递在 AJAX 调用成功时要调用的回调函数,而不是从函数中返回 HTML。

As an example of (2):

以(2)为例:

function findPrice(productId, storeId, callback) {
    jQuery.ajax({
        url: "/includes/unit.jsp?" + params,
        cache: false,
        dataType: "html",
        success: function(html) {
            // Invoke the callback function, passing the html
            callback(productId, storeId, html);
        }
    });

    // Let the program continue while the html is fetched asynchronously
}

function receivePrice(productId, storeId, html) {
    // Now do something with the returned html
    alert("Product " + productId + " for storeId " + storeId + " received HTML " + html);
}

findPrice(23, 334, receivePrice);

回答by Dan F

Short answer, you can't, the first A in AJAX stands for Asynchronous, which means the request is still going when you get to the return statement.

简短的回答,你不能,AJAX 中的第一个 A 代表异步,这意味着当你到达 return 语句时请求仍在进行。

You cando it with a synchronous (non-async) request, but it's generally a Bad Thing

可以使用同步(非异步)请求来实现,但这通常是一件坏事

Something like the following oughta return the data.

像下面这样的东西应该返回数据。

function getPrice(productId, storeId) {
  var returnHtml = '';

  jQuery.ajax({
    url: "/includes/unit.jsp?" + params,
    async: false,
    cache: false,
    dataType: "html",
    success: function(html){
      returnHtml = html;
    }
  });

  return returnHtml;
}


BUT

Unless you really really need to be able to use the return value from test straight away, you'll be muchbetter off passing a callback into test. Something like

除非你真的很需要能够使用从测试的返回值直线距离,你会过传递回调到测试更好。就像是

function getPrice(productId, storeId, callback) {
  jQuery.ajax({
    url: "/includes/unit.jsp?" + params,
    async: true,
    cache: false,
    dataType: "html",
    success: function(html){
      callback(html);
    }
  });
}

//the you call it like
getPrice(x,y, function(html) {
    // do something with the html
}

EditSheesh, you guys are quicker to say what I said :-)

编辑Sheesh,你们可以更快地说出我所说的 :-)

回答by nickf

Your anonymous function there doeshave access to the returnHtmlvariable in its scope, and so the code there is actually working as you'd expect. Where you're probably going wrong is in your return statement.

您的匿名函数确实可以访问returnHtml其范围内的变量,因此那里的代码实际上按您的预期工作。您可能出错的地方是您的退货声明。

Remember that the Ain AJAXstands for asynchronous, which means that it doesn't happen at the same time. For that reason, the line returnHtml = htmlis actually happening afteryou call return returnHtml;, so returnHtmlis still an empty string.

请记住,一个AJAX表示asynchronous,这意味着它不会在同一时间发生。出于这个原因,该行returnHtml = html实际上是您调用之后发生的return returnHtml;,因此returnHtml仍然是一个空字符串。

It's hard to say what you should do to get this working as you want without seeing the rest of your code, but what you could do is add another callback to the function:

在不查看其余代码的情况下,很难说您应该怎么做才能让这个工作如您所愿,但您可以做的是向该函数添加另一个回调:

function getPrice(productId, storeId, callback) {
    jQuery.ajax({
        url: "/includes/unit.jsp?" + params,
        cache: false,
        dataType: "html",
        success: callback
    });
}

getPrice(5, 1, function(html) {
    alert(html);
});