//get请求
var xhr=new XMLHttpREquest();
xhr.open('get'.'xxx.php?key=');
xhr.onreadystatechange=functon(){
if(xhr.readState==4&&xhr.status==200){
console.log(xhr.responseText);
console.log(xhr.JSON.parse(xhr.responseText);
console.log(xhr.responseXML);
}
xhr.send(null);
}
封装Ajax函数 get和post方法
/**
* ajax工具函数-get
* @param {*} url
* @param {*} data(key1=value1&key2=value2)
* @param {*} success
*/
function get(url, data, success) {
var xhr = new XMLHttpRequest();
if (data) {
url += '?';
url += data;
}
xhr.open('get', url);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
success(xhr.responseText);
}
}
xhr.send(null);
}
/**
* ajax工具函数-post
* @param {*} url
* @param {*} data (key1=value1&key2=value2)
* @param {*} success
*/
function post(url, data, success) {
var xhr = new XMLHttpRequest();
xhr.open('post', url);
if (data) {
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
success(xhr.responseText);
}
}
xhr.send(data);
}
jQuery的ajax使用方法
$.ajax({
url:'../....?',
data:{
name:'xiyangyang',
skill:'maimeng'
},
success:function(data){
console.log(data);
},
//参1:异步对象
//参2:错误信息
//参3:错在哪里
error:function(XMLHttpRequest,textStatus,errorThrown){
console.log('失败了哦!')
},
complete:function(){
console.log('请求完成了!');
}
})