这是我用来对 PHP 进行 AJAX 调用的 javascript:
$(document).ready(function(e) {
$(function(){
$.ajax({
type:'GET',
dataType: 'jsonp',
data: {
country: "uk"
},
url: 'http://api.mysite.uk/advertorial/index.php',
success: function (response){
var result = $.parseJSON(response);
console.log(result);
},
error : function () {
console.log('Error');
}
});
});
});
它返回一个如下结构的 JSON:
{"id":"1","name":"test","country":"uk","header":"Header","pre_cta_text":"Pre CTA","cta_text":"CTA text","cta":"CTA","img":null,"active":"1"}
即使调用出现错误,我也可以看到它返回了上面的 JSON。我特别在浏览器控制台中收到的错误是:
Uncaught SyntaxError: Unexpected token : index.php?callback=jQuery32103297264247416809_1516181997373&country=uk&_=1516181997374:1
最佳答案
您指示 jQuery 请求 JSONP 并自动解码它:
dataType: 'jsonp',
然后你获取 jQuery 的解码数据并将其作为 JSON 处理,这不是也从来没有:
success: function (response){
var result = $.parseJSON(response);
console.log(result);
}
关于javascript - 调用返回 JSON 的 PHP 会返回错误,但我可以看到响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48297964/