【问题标题】:Can't get JSON array from URL无法从 URL 获取 JSON 数组
【发布时间】:2013-05-28 20:30:13
【问题描述】:

我正在使用 Resteasy,我在 URL 中启动了一个资源:'localhost:8080/ressources/agences'

当我在浏览器中测试时,我得到:

[{"agence":"Agence Kettani","ville":"Agadir","adresse":"Cartier Hassan II, Agadir","tel":"0528252828","fax":null,"idBanque":1,"id":1},
     {"agence":"Abbatoire","ville":"Agadir","adresse":"Abbatoire, 358 ","tel":"0528283569","fax":null,"idBanque":2,"id":2}]

但是当我尝试使用 jQuery 获取数组时,我得到了这个:

readyState
    0

responseText
    ""

status
    0

statusText
    "error"

abort
    function()

always
    function()

complete
    function()

done
    function()

error
    function()

fail
    function()

getAllResponseHeaders
    function()

getResponseHeader
    function()

isRejected
    function()

isResolved
    function()

overrideMimeType
    function()

pipe
    function()

promise
    function()

setRequestHeader
    function()

statusCode
    function()

success
    function()

then
    function()

这就是我在 Firebug 中所做的:

$.get('http://localhost:8080/Paie1Web/ressources/agences', function(data) {
  return alert(data);
});

我已经测试过getJSON 和 AJAX。我该如何纠正这个问题?

【问题讨论】:

  • 尝试使用$.getJSON 而不是$.get。这应该设置 data 等于 JSON 数组。
  • 我认为控制台显示的是 $.get 的返回,而不是实际 http 请求的返回。
  • 试试$.get('http://localhost:8080/Paie1Web/ressources/agences', console.log); 看看它是否被记录。
  • 您的网页页面是从哪个域加载的?不是 JSON 数据,而是请求它的网页。如果不是 localhost:8080 - 与 JSON 数据相同 - 那么您就有跨站点问题。
  • 这不是返回数据。您正在打印的似乎是一个“承诺对象”。似乎缺少您没有在这里告诉我们的代码。

标签: javascript jquery json rest


【解决方案1】:

有时成功时,由于延迟、服务器速度下降等原因,ajax 有效负载尚未加载,因此您需要处理可以使用 complete 或 done(取决于您使用的版本),可能像这样:

var payload = {};
$.get('http://localhost:8080/Paie1Web/ressources/agences', function(data) {
   $.extend(
      true,      //this forces the object to be deep copied
      payload,   //the target object to extend
      data       //Extend to this object
   );
}, 'json').complete(function(){
   //do what ever you want here with the extended payload
});

我认为这会起作用

【讨论】:

  • 我以前从未见过这种情况。
猜你喜欢
  • 2014-05-28
  • 2017-10-11
  • 2019-10-17
  • 1970-01-01
  • 1970-01-01
  • 2013-07-14
  • 2014-07-12
  • 1970-01-01
  • 2018-02-24
相关资源
最近更新 更多