Original http://www.cnphp6.com/archives/65409
jquery uses the Ajax method to implement JSONP request data across domains when the error "Uncaught syntaxerror:unexpected token:" The main problem is that the returned data is not properly formatted
Local virtual two domain names, respectively: www.test.com, www.abc.com
http://www.test.com/index.html page clicks the button, requests returns the www.abc.com domain name directory The file the data, its code is:
<! DOCTYPE html>
The http://www.abc.com/json.php file code is:
<?php
$arr = Array (' username ' => ' Jack ', ' age ' =>21, ' gender ' => ' Male ');
echo Json_encode ($arr);
? >
In Chrome browser debugging will find an error, as shown in figure:
The data returned by json.php is indeed JSON-type data {"username": "Jack", "Age": "Gender": "Male"}, where is the problem.
Look through the jquery document found Jsonp: "Callback", Jsonpcallback: "Success_jsonpcallback", passed the two parameters for a reason, the JSONP return data format should be: " callback method name (JSON data) passed by the client, change the PHP file to:
<?php
$arr = Array (' username ' => ' Jack ', ' age ' =>21, ' gender ' => ' Male ');
Echo $_get[' callback ']. " (". Json_encode ($arr).");
? >
Test, return the result correctly, as shown below:
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 passing the parameters of the past.
Focus on the main three parameters:
DataType: "Jsonp",
Jsonp: "Callback",
jsonpcallback: "Success_jsonpcallback",
Example:
$.ajax ({
Type: "POST",
url:domain+ "/member_login.action",
Data: {
Loginname:username,
Password:password,
Apptype:2
},
DataType: "Jsonp",
JSONP: "Callback",//passed to the request handler or page to obtain the parameter name of the JSONP callback function name (general default: Callback)
Jsonpcallback: "Flighthandler",//Custom JSONP callback function name, default to jquery automatically generated random function name, also can write "?", jquery will automatically process the data for you
ContentType: "Application/json;charset=utf-8",//Transfer value method
Async:true,
Success:function (msg) {
Alert (msg);
alert (msg.member.memberName);
Console.log (msg);
if (msg== "") {
Alert ("Account password is incorrect.) Login failed! ");
}else{
}
}
});
Sevlet the end of the wording:
Response.getwriter (). Append ("Flighthandler (" +jsonstring+ ")");