javascript - 在 ajax 中使用两个 URL

标签 javascript ajax

我必须从两个不同的 URL 获取值,然后将其合并。我知道如果我在一个 URL 中获取所有数据会更好,但这就是我所拥有的方式,我需要使用它。

我想打印出a_value的值,但是打印出来了,而b还没有返回他的值。我已经阅读了一些关于如何使函数同步的文章,但仍然不知道如何将其实现到我的代码中,也不知道什么是适合我的情况的最佳解决方案。我是 JavaScript 的新手,仍然需要一些帮助和指导。

  function any_function() {
        $.ajax(
            {
                url : '/url1',
                type: "GET",
                success:function(data, textStatus, jqXHR)
                {
                    $("#print").html(a(data));
                }
            });
        }


    function a(data){

        x = 'any value' //`do something with data and insert to this variable`
        a_value =  x + b(`some id that extracted from data`)

        return a_value
    }


  function b(id){
    $.ajax({
                url: '/url2', 
                type: 'GET',
                success: function (data, textStatus, jqXHR) {
                    b_value = c(data, id)  
                }
            });
   return b_value
  }


  function c(data, id){
        //do something with `data` and return the value
        return c_value
    }

最佳答案

function f() {
    var request1 = $.ajax({
        url : '/url1',
        type: 'GET'
    });
    var request2 = $.ajax({
        url: '/url2', 
        type: 'GET'
    });
    $.when(request1, request2).done(function(result1, result2){
        data1 = result1[0]
        data2 = result2[0]
        // r1 and r2 are arrays [ data, statusText, jqXHR ]
        // Do stuff here with data1 and data2
        // If you want to return use a callback or a promise
    })
}

关于javascript - 在 ajax 中使用两个 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36239196/

相关文章:

javascript - Angular IFrame ng-src : Interpolate Error

javascript - WebSocket 握手 : Unexpected response code: 404

ajax 的 python-flask 示例

javascript - 在 WordPress 中单击“发布”时发送 Ajax

javascript - 通过 ajax 加载内容时 jQuery 的本地时间插件失败

javascript - 如何动态地将组件添加到另一个组件的div中?

javascript - 如何在 html 页面之间设置自定义预加载器?

javascript - 从 MongoDB 检索 Docker 日志

javascript - knockout 嵌套组件 : $(document). Ready() ...在加载嵌套组件之前运行

javascript - 添加新 <tr> 时如何使用 jquery 获得不同的时间?