如何在Javascript中解析JSONp响应

时间:2018-06-08 08:01:11

标签: javascript jquery json jsonp

我是Javascript的新手(ish),我正试图从另一个网站的Extrernal API中获取数据,解析它并在我的HTML页面中显示它的块。目前,一切正常,除了我试图从JSONp响应中获取信息以更新HTML显示之外。

我正在使用的JavaScript代码:

//Fetch method grabs information from "myURL"
fetch("https://exampleURL.com", {
    mode: 'cors'
  })
  .then(function(response) {
    if (response.ok) //Checking if response is returned correctly
    {
      var res = response; //Storing response in a variable
      jQuery000000000000000_0000000000(res); //Sending response parsing function
    }
  });


//Parsing function reads the 'title' data from the JSONp response
function jQuery000000000000000_0000000000(res) {
  document.getElementById('title').innerHTML = res[0].title; //Error occurs here
}

我应该从外部API获取JSONp响应:

jQuery000000000000000_0000000000([{"isSuffix":false,"name":"name","title":"Mr"}]);

每当我运行此代码时,我得到一个“Uncaught(in promise)TypeError:无法在控制台中读取未定义的属性'title'错误”,在上面的代码中引用innerHTML行。

任何指针都将非常感谢! :)

[编辑]从我在网上的其他答案中读到的,我认为创建一个与响应中的名称相同的函数是合适的(jQuery000000000000000_0000000000(res);)。我不确定这是否正确。

回复来自外部网站。谢谢!

1 个答案:

答案 0 :(得分:0)

在这种情况下,它是一个JSONP请求。您只需在需要时调用<script>文件。

<script src="/path/to/jsonp.js"></script>

该脚本是可执行的。因此,您不需要使用AJAX或任何类型来调用它。看看你如何发送res?你做错了。这是因为您已在响应中进行了正确的调用:

jQuery000000000000000_0000000000([{"isSuffix":false,"name":"name","title":"Mr"}]);

上面的代码需要执行。请勿使用fetch()

您的完整代码应为:

<script>
  //Parsing function reads the 'title' data from the JSONp response
  function jQuery000000000000000_0000000000(res) {
    document.getElementById('title').innerHTML = res[0].title; //Error occurs here
  }
</script>
<script src="/path/to/jsonp.js"></script>

执行上述内部脚本的另一种方法是使用:

//Parsing function reads the 'title' data from the JSONp response
function jQuery000000000000000_0000000000(res) {
  document.getElementById('title').innerHTML = res[0].title; //Error occurs here
}
$.getScript("/path/to/jsonp.js");

上述文件中的内容将自动使用有效参数调用jQuery000000000000000_0000000000(res)函数。 :)

详细说明

在您当前的代码中,发生的是,您对JSONP请求执行AJAX调用,您不应该这样做,并且它会以这种方式生成代码:

jQuery000000000000000_0000000000("jQuery000000000000000_0000000000([{"isSuffix":false,"name":"name","title":"Mr"}])");

当它尝试访问第一个元素的title属性时,这是一个字符串,在这里,它将是undefined。因为,字符串不会有title属性。

这是堆栈:

jQuery000000000000000_0000000000(jQuery000000000000000_0000000000([{"isSuffix":false,"name":"name","title":"Mr"}]));
res = jQuery000000000000000_0000000000([{"isSuffix":false,"name":"name","title":"Mr"}]);
res[0] = undefined;
res[0].title = TypeError;

这就是你未定义的原因...... :)