Original http://www.cnphp6.com/archives/65409
jquery uses the Ajax method to implement JSONP cross-domain request data when the error "Uncaught syntaxerror:unexpected token:", the main problem is that the returned data format is incorrect
Local virtual two domain names, respectively: www.test.com, www.abc.com
Http://www.test.com/index.html page Click button, request to return the data of the file under the www.abc.com domain name directory, the code is:
<! DOCTYPE html><Html><Head><Metacharset="Utf-8"/><TITLE>JSONP Cross-domain requests</Title><ScriptSrc="Http://www.oschina.net/js/2012/jquery-1.7.1.min.js"Type="Text/javascript" ></Script><ScriptType="Text/javascript" >$(Function () {$ (". Button"). On ("Click",function () {$.ajax ({type:"Get", url:"Http://www.abc.com/json.php", DataType:"Jsonp", Jsonp:"Callback", Jsonpcallback:"Success_jsonpcallback", Success:function (JSON) {$ (". User"). HTML (function () {alert ( "Request Error!) "); } }); }); }); </script></head><body> <button class= "button" > click Get Data </ button> <div class= "user" ></div></ body></HTML>
The http://www.abc.com/json.php file code is:
Array (' username ' = 'Jack ',' age ', ' + ',' gender ' +echo json_encode ($arr);? >
Debugging in the Chrome browser will find an error,
The data returned by json.php is indeed a JSON-type data {"username": "Jack", "Age": $, "gender": "Male"}, where is the problem?
Look at it. jquery Document Discovery Jsonp: "Callback", Jsonpcallback: "Success_jsonpcallback", pass these two parameters for a reason, JSONP the return data format should be: " The client passes the callback method name (JSON data) and changes the PHP file to:
Array (' username ' = 'Jack ',' age ' = ',' gender ' = '$_get[' callback ']." (". Json_encode ($arr).") "; ?>
Test, return the results correctly, such as:
As you can see, the result of the PHP file return is Success_jsonpcallback ({"username": "Jack", "Age": $, "gender": "Male"}), which is the correct JSONP return format, and Success_ Jsonpcallback This is the pass-through parameter.
JSONP cross-domain Request data Error "unexpected token:" Solution