代码之家  ›  专栏  ›  技术社区  ›  Shaun Mundi

jquery ajax成功匿名函数作用域

  •  38
  • Shaun Mundi  · 技术社区  · 16 年前

    如何从Anonymous Success函数中更新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;
    }
    
    3 回复  |  直到 9 年前
        1
  •  61
  •   Luffy Bryan    10 年前

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

    1. 使Ajax调用同步( 未推荐的 ) async: false 选项;或
    2. 改变你的思维方式。当Ajax调用成功时,您需要传递一个回调来调用,而不是从函数返回HTML。

    例如(2):

    function findPrice(productId, storeId, callback) {
        jQuery.ajax({
            url: "/includes/unit.jsp?" + params,
            cache: false,
            dataType: "html",
            success: function(html) {
                callback(productId, storeId, html);
            }
        });
    }
    
    function receivePrice(productId, storeId, html) {
        alert("Product " + productId + " for storeId " + storeId + " received HTML " + html);
    }
    
    findPrice(23, 334, receive_price);
    
        2
  •  14
  •   Dan F    11 年前

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

    可以 使用同步(非异步)请求执行,但通常是 坏事

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

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

    但是

    除非您真的需要立即使用测试返回值,否则您将 许多的 最好将回调传递到测试中。类似的东西

    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
    }
    

    编辑 希什,你们说我说的话要快一点。

        3
  •  12
  •   Luffy Bryan    10 年前

    你在那里的匿名功能 有权访问 returnHtml 变量在其范围内,因此那里的代码实际工作正如您所期望的那样。你可能出错的地方在你的报税表上。

    记住 在里面 阿贾克斯 代表 asynchronous 这意味着它不会同时发生。因为这个原因, returnHtml = html 真的发生了 之后 你打电话 return returnHtml; 如此 返回HTML 仍然是空字符串。

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

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