Ajax
一、 javaScript原生使用Ajax
1.get方法
//1.創(chuàng)建對象 兼容處理
var xhr = null;
//處理低版本IE不兼容問題
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
//2.準備發(fā)送
xhr.open('get','xxx.php?username=' + usernameValue ,true);
//3.執(zhí)行發(fā)送
xhr.send(null);
//4.回調
xhr.onreadystatechange = function () {
/*xhr.readyState == 4 是表示數(shù)據(jù)解析完成浴骂,后臺處理完成了钱磅。
xhr.status == 200 是表示處理的結果是OK的梦裂。響應成功*/
if (xhr.readyState == 4){
if(xhr.status == 200){
//返回結果
var result = xhr.responseText;
console.log(result);
}
}
};
2.post方法
//#1.創(chuàng)建對象 兼容性
var xhr = null;
//處理低版本IE不兼容問題
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject("Microsoft.XMLHTTP")
}
//#2.準備發(fā)送
xhr.open('post','xxx.php',true);
var param = 'phone=' + phoneValue;
//設置響應頭
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
//#3.執(zhí)行發(fā)送
xhr.send(param);
//#4.回調函數(shù)
xhr.onreadystatechange = function () {
if(xhr.readyState == 4){
if(xhr.status ==200){
var result = xhr.responseText;
console.log(result);
}
}
}
open()方法
后面的參數(shù)true
和false
,表示異步和同步,**同步(false
)就是先吃完飯才能看電視盖淡,異步(true
)就是邊吃飯邊看電視****
二年柠、 jQuery中的Ajax
1.基本使用方法
$.ajax({
url: 'xxx.php',
type: 'get',
beforeSend: function(xhr){
console.log(xhr);
},
success: function (res) {
console.log(res);
},
error:function (xhr) {
console.log(xhr);
},
complete:function (xhr) {
console.log(xhr);
}
});
post
方式只需把type
值改成 post
就行
2.快捷方式
$.get('xxx.php',{id:1},function (res) {
console.log(res);
});
$.post('xxx.php',{id:1},function (res) {
console.log(res);
});
以上是
get
和post
兩種方式
3.解析Json格式
$.getJSON('xxx.php',{id:1},function (res) {
console.log(res);
});
或者在放置json格式文件的php中進行申明頭部
<?php
$zhangsan = array(
'name' =>'張三',
'age' =>18
);
//格式
header('Content-Type:application/json');
echo json_encode($zhangsan);
?>