如何在 Javascript 中解析 JSONp 响应



我是Javascript的新手,正在尝试从另一个网站的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"}]);

每当我运行此代码时,我都会在控制台中收到"未捕获(承诺(类型错误:无法读取未定义的属性'title'"错误,引用上面代码中的 innerHTML 行。

任何指示将不胜感激! :)

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

响应来自外部网站。谢谢!

在本例中,这是一个 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.因为,字符串将没有标题属性。

下面是堆栈:

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;

这就是你变得不定义的原因...:)

最新更新