jQuery ajax成功匿名函数范围

Sha*_*n F 38 ajax jquery

如何从匿名成功函数中更新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;
}
Run Code Online (Sandbox Code Playgroud)

cle*_*tus 63

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

  1. 使用该选项使AJAX调用同步(不推荐)async: false; 要么
  2. 改变你的思维方式.而不是从函数返回HTML,您需要传递一个回调,以便在AJAX调用成功时调用.

作为(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);
Run Code Online (Sandbox Code Playgroud)

  • @cletus 你不能说不推荐。仅当用户不需要知道发出请求时才推荐使用。但是在某些情况下需要 async:false 。在不允许用户继续或触发其他事件的情况下,这是必要的。 (2认同)

Dan*_*n F 14

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

可以使用同步(非异步)请求来执行此操作,但这通常是一件坏事

像下面的oughta返回数据.

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;
}
Run Code Online (Sandbox Code Playgroud)

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

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
}
Run Code Online (Sandbox Code Playgroud)

编辑 Sheesh,你们快点说出我说的话:-)


nic*_*ckf 12

您的匿名函数确实可以访问returnHtml其范围内的变量,因此其中的代码实际上正如您所期望的那样工作.你可能出错的地方在你的退货声明中.

请记住,一个AJAX表示asynchronous,这意味着它不会在同一时间发生.出于这个原因,这条线returnHtml = html实际上是你打电话发生的return returnHtml;,所以returnHtml仍然是一个空字符串.

很难说你应该做什么来让你的工作按照你想要的方式工作,而不会看到你的其余代码,但你可以做的是为函数添加另一个回调:

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);
});
Run Code Online (Sandbox Code Playgroud)