Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
776 views
in Technique[技术] by (71.8m points)

jquery - $.ajax and JSONP. ParseError and Uncaught SyntaxError: Unexpected token :

First of all, I've been looking for the answer to my problem in several topics and I couldn't find a solution that works with my code.

I'm trying to get the answer from a servlet, if I go to http://XXXZZZ/Servlet/Login?login=pepe&pass=1234 I receive valid JSON as expected:

{"id":3,"login":"pepe","key":"0D1DBA4BE87E02D43E082F9AA1ECFDEB"}

But when I try the same with $.ajax, I get 2 errors.

$.ajax({
    type : "Get",
    url :"http://XXXZZZ/Servlet/Login",
    data :"login="+login+"&password="+pass,
    dataType :"jsonp",
    success : function(data){
    alert(data);},
    error : function(httpReq,status,exception){
    alert(status+" "+exception);
    }
});

First error (in the popup window):

parsererror Error: jQuery17104145435250829905_1336514329291 was not called

Second error (in the Chrome console):

Uncaught SyntaxError: Unexpected token : Login 1

(And there is the JSON I'm waiting for).

P.S. I have to use dataType : "jsonp", because if I use "json" I also have problems with the Cross-Domain.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you are using jsonp then the syntax is wrong

You need to return

myJsonMethod({"id":3,"login":"pepe","key":"0D1DBA4BE87E02D43E082F9AA1ECFDEB"});

and also add to your ajax request options

jsonp: false,
jsonpCallback: "myJsonMethod"

so

$.ajax({
    type : "Get",
    url :"http://XXXZZZ/Servlet/Login",
    data :"login="+login+"&password="+pass,
    dataType :"jsonp",
    jsonp: false,
    jsonpCallback: "myJsonMethod",
    success : function(data){
        alert(data);},
    error : function(httpReq,status,exception){
        alert(status+" "+exception);
    }
});

(and of-course fix the success as @voyager noted)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...