简体   繁体   中英

Uncaught SyntaxError: Unexpected token u with Ajax post

I am stumped as to how to solve/diagnose ajax/jquery error.

This is my function:

   var LogIn = {
        Email: $("#Name").val(),
        MobileNo: $("#txtMobileNumber").val(),
        PinCode: '',
        Message: '',
        Success:false
    };
    $.ajax({
        type: "POST",
        crossDomain: true,
        dataType: 'jsonp',
         contentType: "application/json",
        url: "https://a different server domain/api/LoginRequest",
        data: JSON.stringify(LogIn),
        success: function (data) {
            $("#divError").html(data);
        },
        error: function (error) {
            jsonValue = jQuery.parseJSON(error.responseText);
            $("#divError").html(jsonValue);
        }
    });

I get this error:

在此处输入图片说明

jQuery doesn't support using POST and jsonp and the reason for that is very simple: when you inject a <script> tag into the DOM (which is what jQuery does when you use jsonp), the browser will send a GET request to the remote endpoint which has been referred to in the src property of this tag.

So basically you will need to use GET instead:

type: "GET"

Also since the data is sent as query string parameters you should remove the content type:

contentType: "application/json",

and do not JSON.stringify the data.

And here's the full example:

$.ajax({
    type: "GET",
    crossDomain: true,
    dataType: 'jsonp',
    url: "https://a different server domain/api/LoginRequest",
    data: LogIn,
    success: function (data) {
        $("#divError").html(data);
    },
    error: function (error) {
        jsonValue = jQuery.parseJSON(error.responseText);
        $("#divError").html(jsonValue);
    }
});

Of course this will work only if the remote endpoint supports JSONP and the GET verb.

Personally I would recommend using CORS instead of JSONP as it would give you much more options. You will be able to use POST in this case. Please refer to the following material as it seems you are using ASP.NET Web API on the server and trying to make a cross domain AJAX call: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

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