简体   繁体   中英

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

I am using jQuery for GET request and getting a response in json format. 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 >>

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. To clear the things on you JSONP is not json. it is javascript script you can say. If you are using say Php then your php should output like this:

     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. Now in ajax call you should have everything stream-lined. Ajax call should be like this:

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

     });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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