【问题标题】:How to manipulate result from ajax request before jump to .then callback如何在跳转到 .then 回调之前操作来自 ajax 请求的结果
【发布时间】:2019-07-06 10:42:26
【问题描述】:

我正在尝试在我的 ajax 请求的结果上添加一些变量,然后再转到 .then() 回调。但是我的代码总是将 ajax 响应的结果返回给 .then() 语句。

   $.ajax({
            url: "api.php",  //this returning [{"sid":"454545454554"}]
            success:function(data) {
                a = data.push({"additional_var" : "one"});
                return a;
            }
        })
        .then(function(response1){
            console.log(response1);           
        })

上面的代码response1 总是从我的api.php ([{"sid":"454545454554"}]) 返回响应。我希望 response1 在转到 .then() 之前添加 {"additional_var" : "one"}。有什么办法吗?

【问题讨论】:

    标签: javascript ajax callback


    【解决方案1】:

    要么把所有东西都放在.then

        .then(function(response1){
            response1.push({"additional_var" : "one"});
            console.log(response1);           
        })
    

    或者将另一个 .then 链接到开头(这不是一个好主意,除非代码的其他部分单独使用 Promise):

    const prom = $.ajax({
      url: "api.php"
    })
      .then(function(response1){
        response1.push({"additional_var" : "one"});
        console.log(response1);           
      })
    
    prom.then(console.log);
    

    【讨论】:

      【解决方案2】:

      你可以这样做:

      $.ajax({
        url: "api.php"
      }).then(function(data) {
        data.push({
          "additional_var": "one"
        });
        return data;
      }).then(function(response1) {
        console.log(response1);
      })

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-15
        • 1970-01-01
        • 1970-01-01
        • 2013-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多