jQuery封裝的ajax
$.get(url [,data] [,fn回調(diào)函數(shù)] [, dataType]);
data:給服務(wù)器傳遞的數(shù)據(jù),請(qǐng)求字符串 、json對(duì)象 都可以設(shè)置
fn:回調(diào)函數(shù),ajax請(qǐng)求完成后調(diào)用該函數(shù),可以在此函數(shù)完成ajax的后續(xù)處理
dataType:服務(wù)器返回?cái)?shù)據(jù)類型,html、text、xml、json
注:該ajax是異步的get方式請(qǐng)求
$.post(url[,data][,fn回調(diào)函數(shù)][, dataType]);
該方法與$.get()方法使用完全一致,不同的是其為post方式請(qǐng)求
$.ajax({ //json對(duì)象
url:請(qǐng)求地址,
data:給服務(wù)器傳遞的數(shù)據(jù),
dataType:數(shù)據(jù)從服務(wù)器返回格式html、text、xml、json
type:get/post請(qǐng)求方式
success:function(){} ajax成功請(qǐng)求后的回調(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:'小強(qiáng)',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完成請(qǐng)求的“回調(diào)函數(shù)” //msg是自定義變量,代表從服務(wù)器返回的信息 // 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代表服務(wù)器返回的信息 alert(msg.name+"--"+msg.age); } }); } </script> <style type="text/css"> </style> </head> <body> <h2>ajax請(qǐng)求</h2> <input type="button" value="請(qǐng)求1" onclick="f1()" /> <input type="button" value="請(qǐng)求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); ?>
注:大家可以將這兩個(gè)文件復(fù)制到本地,放在一個(gè)文件夾中進(jìn)行測(cè)試