【发布时间】:2017-08-16 23:26:24
【问题描述】:
我正在创建一个调用远程数据(json)的网页。为此,我使用了 jQuery.ajax,当我在同一个域中调用页面时,这很好。但是,如果我从另一个域(例如:localhost)调用它,浏览器会通过说来阻止
请求的资源上没有“Access-Control-Allow-Origin”标头
但如果我将 dataType: 'JSONP' 与 ajax 一起使用,则浏览器不会阻塞,但会收到此 以下错误,尽管它是一个有效的 json 对象:
Uncaught SyntaxError: Unexpected token :
at p (jquery.min.js:2)
at Function.globalEval (jquery.min.js:2)
at text script (jquery.min.js:4)
at Nb (jquery.min.js:4)
at A (jquery.min.js:4)
at XMLHttpRequest.<anonymous> (jquery.min.js:4)
这是我的 ajax 代码:
$(function () {
$.ajax({
url: "/GarmentTech/api/get_products.php",
type: "GET",
success: function (result) {
$('.text').text('');
console.log(result);
console.log(result);
for (var i = 0; i < result.products.length; i++) {
var place = `
<tr>
<td>${result.products[i].name}</td>
<td>${result.products[i].description}</td>
<!--<td>${result.products[i].type}</td>-->
<td>${result.products[i].model_color}</td>
<td>${result.products[i].size}</td>
<!--<td>${result.products[i].manufacturer}</td>-->
<td>${result.products[i].purchase_rate}</td>
<td>${result.products[i].sales_rate}</td>
<td style="text-align:right;">
${result.products[i].stock_count}
${result.products[i].unit_type}
</td>
</tr>
`;
$('.product_view').append(place);
}
},
dataType: 'JSONP' // <----
});
});
而json是这样的:
{
"status": "ok", //<---- (chrome is saying problem is hare)
"count": 26,
"count_total": 26,
"pages": 1,
"products": [
{
"size": "16X18",
"id": 41,
"name": 86416,
"cost_price": 1200,
"sales_rate": 1300,
"description": "",
"remarks": "",
"batch_no": "NA"
}, {}...
【问题讨论】:
-
它可能是有效的 JSON,但它不是有效的 JSONP。
-
谢谢@JJJ,我找到了解决方案。问题解决了。刚刚添加了这一行
<?php header('Access-Control-Allow-Origin: *'); ?>
标签: javascript jquery json ajax