首页 > 解决方案 > 如何使用通过 jQuery.get 调用获得的 URL 来执行另一个调用?

问题描述

基本上,我想做的是:

var mydata = null;
jQuery.get(ANOTHER_URL, function(data) {
    mydata = data;
}).then(jQuery.get(parsingFunction(mydata), function(otherData) {/*do stuff with otherData*/}));

parsingFunction(notYetAnURL) {
   /*does stuff with notYetAnUrl*/
   return nowIsURL;
}

问题是..这不起作用。当第二个 jQuery.get 调用发生时,mydata似乎仍然是null. 我是 Ajax 和一般异步编程的新手,所以如果这个问题看起来很愚蠢,我深表歉意,但我真的无法摆脱这个问题。有人可以帮忙吗?

标签: jqueryajaxasynchronous

解决方案


您没有为结果使用回调函数。因此,最好使用回调函数.done.fail功能,以获得更好的可读性和错误捕获。

function firstService(){
  jQuery.get(ANOTHER_URL)
    .done(function(data){
      // first result
      if(data){
        secondService(data);
      }
    })
    .fail(function(xhr, status, error) {
      console.log(xhr);
      console.log(status);
      console.error(error);
  });
}

function secondService(newData){
  jQuery.get(getSecondServiceUrlFromData(newData))
    .done(function(data){
      // second result
    })
    .fail(function(xhr, status, error) {
      console.log(xhr);
      console.log(status);
      console.error(error);
  });
}

function getSecondServiceUrlFromData(data) {
   /*does stuff with notYetAnUrl*/
   return nowIsURL;
}

firstService();

推荐阅读