我遇到了一个问题,即我无法使用以下代码访问以下JSON。我可以在我的网络查看器中看到JSON并且没有错误,但是在apiReturn函数中没有任何运行,我无法找出原因。
/**/
({
"batchcomplete": "",
"query": {
"normalized": [{
"from": "mouse",
"to": "Mouse"
}],
"pages": {
"18845": {
"pageid": 18845,
"ns": 0,
"title": "Mouse",
"extract": "<p>A <b>mouse</b> (plural: <b>mice</b>) is a small rodent characteristically having a pointed snout, small rounded ears, a body-length scaly tail and a high breeding rate. The best known mouse species is the common house mouse (<i>Mus musculus</i>). It is also a popular pet.</p>"
}
}
}
})
$.getJSON("https://en.wikipedia.org/w/api.php?action=query&origin=*&format=json&exsentences=3&prop=extracts&titles=Main+Page&callback=&titles=mouse", function(apiReturn){
var valueText = apiReturn.query.pages[18845].extract;
console.log(valueText);
});
答案 0 :(得分:0)
这不是JSON,它是JSONP。它不起作用的原因是查询字符串中有一个空callback
个参数。将&callback=&titles=mouse
更改为&callback=?&titles=mouse
(请注意?
之后的callback=
),jQuery会正确处理它。 E.g:
$.getJSON("https://en.wikipedia.org/w/api.php?action=query&origin=*&format=json&exsentences=3&prop=extracts&titles=Main+Page&callback=?&titles=mouse", function(apiReturn){
// Only change is here ---------------------------------------------------------------------------------------------------------------^
var valueText = apiReturn.query.pages[18845].extract;
console.log(valueText);
});
更多:http://api.jquery.com/jQuery.getJSON和http://api.jquery.com/jQuery.ajax
答案 1 :(得分:0)
确保服务器正在检索正确的json数据,因为使用外部假json的代码对我来说没问题。 json的响应肯定存在问题。
var fakeJsonData = "https://jsonplaceholder.typicode.com/posts/1";
$.getJSON(fakeJsonData, function(apiReturn){
var valueText = apiReturn.body;
console.log(valueText);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
答案 2 :(得分:0)
请添加:&amp; callback =?在网址的末尾。
代码如下:
java.lang.NullPointerException