weixin_33675507 2016-03-26 18:32 采纳率: 0%
浏览 341

使用Ajax中的两个URL

I have to get values from two different URLs and then to merge it. I know it would much better if i'll get all of the data in one URL, but that's how i've got and i need to work with it.

I want to print out the value of a_value, but it's been printed out while b hasn't returned his value. I've read some articles of how to make the functions synchronous but still don't know how to implement it into my code, and don't know what is the best solution for my case. I'm pretty new with JavaScript and still need some help and guiding.

  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
    }
  • 写回答

3条回答 默认 最新

  • 零零乙 2016-03-26 18:38
    关注

    This can be done in a synchronous-looking fashion with promises:

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

报告相同问题?

问题事件

  • 请选择合适的标签 12月7日