Before I wrote "PHP return JSON data Simple instance", "PHP returns JSON data in Chinese display problem" and "use JSON in PHP language and restore JSON to an array". Interested children's shoes can see
Today I am writing an instance of PHP AJAX Jsonp used. I don't know what JSONP is, please search by yourself
Example 1
Test.html
<!doctype html>
Ajax.js
$.ajax ({type: "post", url: "ajax.php", DataType: "Jsonp", Jsonp: "Callback",//passed to the request handler or page, to obtain the name of the JSONP callback function name (default: Callback) Jsonpcallback: "Success_jsonpcallback",//Custom JSONP callback function name, default to jquery automatically generated random function name Success:function (JSON) { Alert (' success ');},error:function () {alert (' fail ');}});
ajax.php
<?php $data = "..."; $callback = $_get[' callback '];echo $callback. ' ('. Json_encode ($data). ') '; Exit;? >
Jquery-1.5.2.min.js
Download your own Internet
When using JSONP, the function is called with JSONP form, such as "myurl?callback=?" JQuery is automatically replaced? is the correct function name to execute the callback function.
Example 2
Test.html
<!doctype html>
Ajax.js
$ (document). Ready (function () { $ ("#btn"). Click (function (k) { //... var j = $ ("form"). Serializearray ();//serialization of Name/value $.ajax ({type: ' GET ', //here with Geturl: ' ajax.php ', DataType: ' Jsonp ', //Type DATA:J,JSONP: ' Callback ',//jsonp callback parameter, required async:false, success:function (Result) {//Return JSON Data alert (result.message);//callback output result = Result | | {}; if (result.msg== ' err ') { alert (result.info); } else if (result.msg== "OK") { alert (' Commit succeeded '); } else{ alert (' Submission failed '), } },timeout:3000 }) //... });
ajax.php
<?php$callback = Isset ($_get[' callback ')? Trim ($_get[' callback '): "; The JSONP callback parameter, required for the = Array ("Age" of =>$_get[' age '), "message" =>$_get[' age '), $date ["MSG"]= "err"; $date ["Info"]= "Due to character problem, send failed"; $tmp = Json_encode ($date); echo $callback JSON data. ' ('. $tmp. ') '; Return format, required?>
Jquery-1.5.2.min.js
Download yourself from the Internet