jQuery ajax 成功匿名函数作用域 [英] jQuery ajax success anonymous function scope

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

问题描述

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

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

推荐答案

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

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:

  1. 使用 不推荐)"noreferrer">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) {
            // 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);

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

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