0

I'm a new jser and now I have trouble in how to realize ajax POST and GET. I can POST and GET the data through google postman like that getpost.

but I am failed to get the data through jquery ajax, the error is 'Uncaught SyntaxError: Unexpected token :'. It get response but jump to the error function. I find many solution but could I realize to POST and GET without changing the background interface just like the Google postman?

    $(function(){
    $.ajax({
        url: "http://115.29.203.53:10013/students",
        type: "GET",
        async: false,
        dataType: "jsonp",
        success: function(json){
            console.log(json);
        },
        error: function(){

        }
    });
});

Thanks for reading my question and please forgive my broken English!

Entwickler
  • 255
  • 2
  • 12
yzajoee
  • 88
  • 5

1 Answers1

0

What you are trying to do is to make a cross-domain access using ajax. This is not possible. You can make cross-domain request by setting

dataType : "JSONP"

but JSONP format is like functionname({"a": 1, b: {c: 2}). Which mean that JSON object should be in curly braces () with some callback function. Therefore, you are getting

"Uncaught SyntaxError: Unexpected token :"

For making cross-domain request, one needed to added Http header ('Access-Control-Allow-Origin: *'). Then you would be able to make cross-domain requests with dataType JSON.

Your AJAX then look like this.

 $(function () {
            $.ajax({
                url: "http://115.29.203.53:10013/students",
                type: "GET",
                async: false,
                dataType: "JSON",
                success: function (json) {
                    console.log(json);
                },
                error: function () {
                    console.log("Error");
                },
                crossDomain: true
            });
        });
Entwickler
  • 255
  • 2
  • 12
  • "JSONP format is like ({"a": 1, b: {c: 2})." — No, it isn't. The format of JSONP is "A function name" then `(` then "a JavaScript expression" then `)`. – Quentin Feb 24 '16 at 08:28
  • "For making cross-domain request, one needed to added Http header" — Not if your are using JSONP. (JSONP is a dirty hack and you should use CORS instead, but the Access-Control stuff is for when you are doing it properly). – Quentin Feb 24 '16 at 08:29