在以前我寫過「php返回json數據簡單實例」,「php返回json數據中文顯示的問題」和「在PHP語言中使用JSON和將json還原成數組」。有興趣的童鞋能夠看看php
今天我寫的是PHP AJAX JSONP使用的實例。不清楚jsonp是什麼的請本身搜索html
實例1jquery
test.htmlajax
1json 2數組 3async 4函數 5post 6jsonp 7 8 9 10 11 12 |
<! doctype html> < html > < head > < meta charset="utf-8"> < title >test</ title > < script src="jquery-1.5.2.min.js"></ script > < script src="ajax.js"></ script > </ head > < body > </ body > </ html > |
ajax.js
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$.ajax({ type : "post" , url : "ajax.php" , dataType : "jsonp" , jsonp: "callback" , //傳遞給請求處理程序或頁面的,用以得到jsonp回調函數名的參數名(默認爲:callback) jsonpCallback: "success_jsonpCallback" , //自定義的jsonp回調函數名稱,默認爲jQuery自動生成的隨機函數名 success : function (json){ alert( 'success' ); }, error: function (){ alert( 'fail' ); } }); |
ajax.php
1 2 3 4 5 6 7 8 |
<?php $data = "......." ; $callback = $_GET [ 'callback' ]; echo $callback . '(' .json_encode( $data ). ')' ; exit ; ?> |
jquery-1.5.2.min.js
本身上網下載
當使用jsonp時,使用 JSONP 形式調用函數時,如 "myurl?callback=?" jQuery 將自動替換 ? 爲正確的函數名,以執行回調函數。
實例2
test.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<! doctype html> < html > < head > < meta charset="utf-8"> < title >test</ title > < script src="jquery-1.5.2.min.js"></ script > < script src="ajax.js"></ script > </ head > < body > < form name="form"> < input type="text" name="sex"> < input type="text" name="age"> < input type="button" id="btn" value="button" /> </ form > </ body > </ html > |
ajax.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
$(document).ready( function (){ $( "#btn" ).click( function (k) { //... var j = $( "form" ).serializeArray(); //序列化name/value $.ajax({ type: 'GET' , //這裏用GET url: 'ajax.php' , dataType: 'jsonp' , //類型 data: j, jsonp: 'callback' , //jsonp回調參數,必需 async: false , success: function (result) { //返回的json數據 alert(result.message); //回調輸出 result = result || {}; if (result.msg== 'err' ){ alert(result.info); } else if (result.msg== "ok" ){ alert( '提交成功' ); } else { alert( '提交失敗' ); } }, timeout: 3000 }) //... }); }); |
ajax.php
1 2 3 4 5 6 7 8 |
<?php $callback = isset( $_GET [ 'callback' ]) ? trim( $_GET [ 'callback' ]) : '' ; //jsonp回調參數,必需 $date = array ( "age" => $_GET [ 'age' ], "message" => $_GET [ 'age' ]); $date [ "msg" ]= "err" ; $date [ "info" ]= "因人品問題,發送失敗" ; $tmp = json_encode( $date ); //json 數據 echo $callback . '(' . $tmp . ')' ; //返回格式,必需 ?> |