简体   繁体   English

使用jsonp的Ajax get给出“ SyntaxError:missing; 声明前”错误

[英]Ajax get with jsonp gives “SyntaxError: missing ; before statement” error

I am using jQuery for GET request and getting a response in json format. 我正在使用jQuery进行GET请求并以json格式获取响应。 But when I try to use it, it throws below error message in browser developer tools console. 但是,当我尝试使用它时,它会在浏览器开发人员工具控制台中抛出以下错误消息。

SyntaxError: missing ; 语法错误:丢失; before statement[Learn More] hosts:1:10 >> 声明前[了解更多]主持人:1:10 >>

Below is my code. 下面是我的代码。

$.ajax({
    type: "GET",   
        url: url,   
        async: false,
        cache: false,
        data: { "filter": "host.vars.osgroup==\"unix\""},
        jsonp: "callback",
        dataType: "jsonp",
        contentType: "application/json; charset=utf-8",
        headers: {
            accept:'application/json',
            "Authorization": "Basic " + btoa(username + ":" + password)
        }
        // },
        // success : function(data)
        // {
        //     console.log(data);
        // }

})
 .done(function(html) {
     $("#displayElement").append(html);
 });

This error occures just when the response of the server is not in valid JSONP format. 仅当服务器的响应不是有效的JSONP格式时,才会发生此错误。 To clear the things on you JSONP is not json. 要清除您的东西,JSONP不是json。 it is javascript script you can say. 这是您可以说的javascript脚本。 If you are using say Php then your php should output like this: 如果您使用的是说Php,那么您的php应该输出如下:

     header("Content-Type: application/json");    
     exit("mycallback(".json_encode(['error' => 0,'auth_token' => $_COOKIE['server_token']]).")");

You see that Php code is outputting a string which has javascript function call with json formatted data as parameter. 您会看到Php代码正在输出一个字符串,该字符串具有以json格式的数据作为参数的javascript函数调用。 Now in ajax call you should have everything stream-lined. 现在,在ajax调用中,您应该精简所有内容。 Ajax call should be like this: Ajax调用应如下所示:

     $.ajax({
        url:'http://ssoidpclient.local/get_auth_token',
        dataType: 'jsonp',
        jsonp: false,
        jsonpCallback: 'mycallback',
        success:function(data)
        {
        }

     });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM