【问题标题】:JSONP Utncaught SyntaxError: Unexpected tokenJSONP Utncaught SyntaxError:意外的令牌
【发布时间】:2017-01-19 22:32:25
【问题描述】:

我需要为内部通信创建一个简单的 HTTP GET 请求。

请求打开了一扇门。如果我在浏览器中输入此网址: http://172.27.1.20/api/switch/ctrl?switch=1&action=on 端口打开,浏览器显示它。

{
"success" : true
}

我尝试使用 Ajax 脚本发送 HTTP GET 但控制台日志显示:

ctrl?callback=jQuery1600571…_1473684252251&switch=1&action=on&_=1473685494405:2 Utncaught SyntaxError: Unexpected oken :
 function test() {              
            $.ajax({
                url: 'http://172.27.1.20/api/switch/ctrl',
                type: 'GET',
                data: {switch: 1, action: 'on'},
                crossDomain: true,
                dataType: 'jsonp',
                dataCharset: 'jsonp',
                contentType: 'application/json',
                success: function (result) {
                console.log("OK - RESULT: " + result);
               },
                error: function (result, error) {
                console.log("ERROR - RESULT: " + result + " - TYPE ERROR: " + error);
                }
            });
        }

有人可以帮我吗?

【问题讨论】:

  • 我使用 jsonp 因为我需要从另一个域使用它。
  • 如果对您有帮助,您可以接受下面的答案吗?

标签: java json ajax jsonp


【解决方案1】:

为什么要使用jsonp?这真的需要吗?如果使用 JSONP,必须设置回调函数作为响应。我在 url 中没有看到你的回调函数?

更改网址并添加回调函数

url: http://172.27.1.20/api/switch/ctrl?switch=1&action=on&callback=yourCallbackFunctionName

当 JSONP 服务器收到您的请求并找到回调参数时 - 它不会返回普通的 JS 数组,而是返回:

yourCallbackFunctionName({['success', 'true']});

现在在您的代码中尝试读取下面的数据示例(未测试)代码

success: function(dataSentInJsonp){
                        var len = dataSentInJsonp.length;
                        for(var i=0;i<len;i++){
                            // iterate and get your variables
                              valVariable= dataSentInJsonp[i];
                          }

【讨论】:

    猜你喜欢
    • 2015-08-19
    • 2014-05-27
    • 2014-02-19
    • 1970-01-01
    • 2011-11-21
    • 2017-08-05
    • 2021-03-31
    • 2019-04-20
    • 1970-01-01
    相关资源
    最近更新 更多