在ajax中使用两个URL

Working with two URLs in ajax

本文关键字:两个 URL ajax      更新时间:2023-09-26

我必须从两个不同的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
    })
}

这可以通过promise以同步的方式完成:

$.get(url1)
.then(function(data1){
  return $.get(url2)
})
.then(function(data2){
  return $.get(url3);
})
.then(function(data3){
  // All done
});

您只需要在第一个成功处理程序的成功处理程序中进行第二个调用:

function any_function() {
    $.ajax({
            url : '/url1',
            type: "GET",
            success:function(data, textStatus, jqXHR) {
                $("#print").html(a(data));
                b("someId");
            }
    });
 }
 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
}