javascript - 在一个成功的内部进行 ajax 调用可以被认为是不好的做法吗?

标签 javascript ajax jquery

让我们来看下面的一段代码:

$.ajax({
    type: 'POST',
    dataType: dataType,
    url: 'someUrl',
    success: function(result){
        $.ajax({
            type: 'POST',
            dataType: dataType,
            url: 'anotherUrl',
            data: queryToSearch,
            success: function(anotherResult){
                (do something that uses the first one result)
            },
            error: MyObj.defaultAjaxError
        });
    },
    error: MyObj.defaultAjaxError
    });

这可以被认为是一种不好的做法吗?它对性能有影响吗?如果是,是否有更好的方法来做这样的事情?

最佳答案

使用 promise 。希望,Promises/A (如 implemented in jQuery 1.8+ Deferred Objects ),然后:

$.ajax({..}) // Promise 1
 .fail(function () {
    // Oops! This will fire if (and only if) Promise 1 failed.
 })
 .then(function () {
    // This will only fire if the first request had no error - was "done"
    // We then return a NEW promise for the 2nd request. In a proper
    // Promises/A, 'then' returns a (new) promise. (jQuery < 1.8 is broken.)
    return $.ajax({..}) // Promise 2
 })
 // Note that these are for the 2nd promise which has been returned from
 // the 'then' above OR from a 2nd promise created automatically by the default
 // failHandler.
 .fail(function () {
    // Oops! This will fire if EITHER the promises (AJAX calls) fails.
    // This happens because we are either binding to our Promise 2
    // or to the auto-rejected promise returned from the default failHandler.
 })
 .done(function () {
    // 2nd promise done - means both are done!
 })

使用 when 是不合适的,因为那样会“并行”。 (实际上,when 可以 与“ stub ”promise 一起使用,该 promise 在第二次调用完成时被连接以被接受 - 然而这并没有受益于 then 链接并且不可能有意义地使用来自第二次调用的 promise 直接用于串行执行。)

需要注意的一件有趣的事情是 faildone 只是 then 的简写/限制形式 .这些方法可以(并且应该)用于清晰的意图/代码。

关于javascript - 在一个成功的内部进行 ajax 调用可以被认为是不好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18623202/

相关文章:

javascript - 无法更改动态创建的文本框的值

javascript - 将多个选定选项传递给 Angular 中的 Firebase 查询(AngularFire2)

jquery - fadeOut() 和 fadeIn() 在同一 Action 中

javascript - jquery 选项卡使用绝对位置而不是显示 :none

javascript - 取消特定元素上的事件冒泡 - javascript

javascript - JS 查找丢失的字母(字母表 - 数组)

javascript - 如何在没有 jQuery 的情况下将 ajax 响应文本与某些字符串进行比较

asp.net - 如何使用 jQuery/JSON/AJAX 将字符串传递到 ASP.NET Web 服务

php - 两个Post请求,并且不改变变量

javascript - 由 jQuery 自动生成的多个复选框列表