jQuery封裝的ajax
$.get(url??[,data]??[,fn回調(diào)函數(shù)]???[, dataType]);
data:給服務器傳遞的數(shù)據(jù),請求字符串?、json對象?都可以設置
fn:回調(diào)函數(shù),ajax請求完成后調(diào)用該函數(shù),可以在此函數(shù)完成ajax的后續(xù)處理
dataType:服務器返回數(shù)據(jù)類型,html、text、xml、json
注:該ajax是異步的get方式請求
$.post(url[,data][,fn回調(diào)函數(shù)][, dataType]);
該方法與$.get()方法使用完全一致,不同的是其為post方式請求
$.ajax({??//json對象
url:請求地址,
data:給服務器傳遞的數(shù)據(jù),
dataType:數(shù)據(jù)從服務器返回格式html、text、xml、json
type:get/post請求方式
success:function(){} ?ajax成功請求后的回調(diào)函數(shù),可以做后續(xù)處理使用
async:[true]異步/false同步,
cache:[true]緩存/false不緩存,
})
<!DOCTYPE html> <html> <head> <title>php.cn</title> <meta charset="utf-8" /> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script> <script> function f1(){ //① $.get(url[,data,fn,dataType]) //$.get('./1.php'); //$.get('./1.php','name=tom&age=20',function(msg){ //$.get('./1.php',{name:'小強',age:21},function(msg){ // alert(msg) //}); $.get('/1.php',{name:'小明',age:21},function(msg){ alert(msg.name+"--"+msg.age) },'json'); //$.get('./1.php',function(msg){ //ajax完成請求的“回調(diào)函數(shù)” //msg是自定義變量,代表從服務器返回的信息 // alert(msg); //}); } function f2(){ //$.ajax({url: data: dataType: type:get/post success:}) $.ajax({ url:'/1.php', data:{name:'小方',age:21}, dataType:'json', type:'get', success:function(msg){ //msg代表服務器返回的信息 alert(msg.name+"--"+msg.age); } }); } </script> <style type="text/css"> </style> </head> <body> <h2>ajax請求</h2> <input type="button" value="請求1" onclick="f1()" /> <input type="button" value="請求2" onclick="f2()" /> </body> </html>
php內(nèi)容為:
<?php $name=$_GET['name']; $age=$_GET['age']; $arr =array( 'name'=>$name, 'age'=>$age ); echo json_encode($arr); ?>
注:大家可以將這兩個文件復制到本地,放在一個文件夾中進行測試