【问题标题】:Using jQuery $.when and $.then to handle multiple ajax requests not returning response text使用 jQuery $.when 和 $.then 处理多个不返回响应文本的 ajax 请求
【发布时间】:2016-06-04 17:29:41
【问题描述】:

基本上我想使用 jQuery 从 XML 和 JSON 提要返回数据,console.log 只有在两者都成功时才返回数据。

如果我在$.when 中注释掉getRoomFeed(),它将为XML 返回正确的responseText 对象,但是如果我将它们都留在其中,它会在我console.log(rateData) 时返回文档对象。为什么我不能从 JSON 和 XML 中提取数据并从两者中获取 responseText?为什么我在 $.when 中同时使用两个提要时会得到不同的结果?

查看附加的codepen并检查下面的控制台或代码,

function getRoomFeed() {
 return $.ajax({
type: "GET",
url: "JSONURLHERE.json",
dataType: "JSON"
 });
};

 function getRates() {
  return $.ajax({
type: "GET",
url: "XMLURLHERE.xml",
dataType: "XML"
 });
};

$('#prop__selector').on('change', function() {
  getPropCode = $(this).val();
  $.when(getRoomFeed(), getRates()).then(function(roomData, rateData) {
console.log(roomData);
console.log(rateData);
    }); 
 });

http://codepen.io/benweiser/pen/gPNVmd/

我附上了图片,但不幸的是我不得不删除它们,因为我没有足够的声誉。

【问题讨论】:

    标签: jquery json ajax xml


    【解决方案1】:

    它工作得很好,但是你在每个响应中都从$.ajax 得到三个参数,所以你需要这样做

    console.log(roomData[0]);
    console.log(rateData[0]);
    

    当您添加 dataType 时,jQuery 会解析内容,因此 JSON 已被解析为对象,而 XML 已被解析为 document,这可能就是您看到的文档。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-26
      • 2017-12-08
      • 1970-01-01
      • 1970-01-01
      • 2014-03-12
      • 2014-07-19
      • 2013-02-08
      相关资源
      最近更新 更多