jQuery的阿贾克斯成功匿名函数范围 [英] jQuery ajax success anonymous function scope

查看:151
本文介绍了jQuery的阿贾克斯成功匿名函数范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何从成功的匿名函数内更新returnHtml变量?

 函数用getPrice(productId参数,STOREID){
    VAR returnHtml ='';

    jQuery.ajax({
        网址:/includes/unit.jsp? +参数,
        缓存:假的,
        数据类型:HTML,
        成功:函数(HTML){
            returnHtml = HTML;
        }
    });

    返回returnHtml;
}
 

解决方案

这是错误的做法。在AJAX的第一个A是异步的。 AJAX调用返回之前,该函数返回(或至少它可以)。因此,这不是范围的问题。它的订货的问题。只有两种选择:

  1. 请AJAX调用同步( 不建议)用的 异步:假 选项;或
  2. 在改变你的思维方式。相反,从函数返回的HTML,你需要passin回调当AJAX调用成功被调用。

作为一个例子(2):

 函数findPrice(productId参数,STOREID,回调){
    jQuery.ajax({
        网址:/includes/unit.jsp? +参数,
        缓存:假的,
        数据类型:HTML,
        成功:函数(HTML){
            回调(productId参数,STOREID,HTML);
        }
    });
}

功能receivePrice(productId参数,STOREID,HTML){
    警报(产品+ productId参数+的STOREID+ STOREID +接收到的HTML+ HTML);
}

findPrice(23,334,receive_price);
 

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

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

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

    return returnHtml;
}

解决方案

That's 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 isn't an issue of scope. It's an issue of ordering. There are only two options:

  1. Make the AJAX call synchronous (not recommended) with the async: false option; or
  2. Change your way of thinking. Instead of returning HTML from the function you need to passin a callback to be called when the AJAX call succeeds.

As an example of (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);

这篇关于jQuery的阿贾克斯成功匿名函数范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆