javascript - 未捕获的语法错误 : Unexpected token : jQuery ajax

标签 javascript jquery json ajax

我正在创建一个调用远程数据(json)的网页。为此,我使用了 jQuery.ajax,当我在同一域中调用页面时,它很好。但是如果我从另一个域(例如:localhost)调用它,浏览器会通过说来阻止

No 'Access-Control-Allow-Origin' header is present on the requested resource

但是如果我使用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"
    }, {}...

最佳答案

你不能只使用JSONP,它必须得到服务器的支持。 JSONP 是一种 hack,服务器将 JSON 数据包装在 JavaScript 函数(回调)中。当 jQuery 收到它时,它会对其进行评估并尝试运行该函数。如果您调用的服务器不进行包装,则它将无法工作。因此出现了 token 错误。

如果您可以控制服务器,则可以实现 JSONP 支持或为 AJAX 调用提供适当的跨域支持。这通常称为 CORS (跨源资源共享)。

您可以通过修改访问策略来使 CORS 设置更加宽松。有大量教程介绍如何使用几乎任何 Web 服务器以及几乎任何语言来执行此操作。

关于javascript - 未捕获的语法错误 : Unexpected token : jQuery ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42992466/

相关文章:

javascript - 如何通过匿名函数为对象属性赋值?

jquery - 在 jquery 中动态添加脚本/功能 block

javascript - 如何在 jQuery 中仅触发一次多个事件的回调

javascript - 如何在对象内声明不会注册到 0 索引的数组?

javascript - 将javascript中的对象转换为json对象

javascript - 想要从函数访问变量以在主干中渲染函数

javascript - 如何在 ReactJS 中显示数组中的 HTML

javascript - 从 dom 中隐藏输入值属性

jquery - onmouseover 显示 div 调整 x 和 y

javascript - React - 如何访问数组中的特定位置,然后更改它?