js实现ajax
var xmlHttpReq = null;
if(window.ActiveXObject) {
xmlHttpReq = new ActiveXObject('Microsoft.XMLHTTP');
} else if(window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
}
xmlHttpReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttpReq.open('GET','test.php',true);
xmlHttpReq.onreadystatechange = function(){
if(xmlHttpReq.readyState === 4) {
if(xmlHttpReq.status === 200) {
alert(xmlHttpReq.responseText);
}
}
};
xmlHttpReq.send(null);
例子如下:
submit.onclick = function(){
var xmlHttpReq = null;
if(window.ActiveXObject) {
xmlHttpReq = new ActiveXObject('Microsoft.XMLHTTP');
} else if(window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
}
xmlHttpReq.open('POST','http://10.2.229.82:8088/api/friend',true);
xmlHttpReq.onreadystatechange = function(){
if(xmlHttpReq.readyState === 4) {
if(xmlHttpReq.status === 200) {
alert(xmlHttpReq.responseText);
}
}
};
xmlHttpReq.send("a=1,b=2");
};
如果要设置请求头的话:
submit.onclick = function(){
var xmlHttpReq = null;
if(window.ActiveXObject) {
xmlHttpReq = new ActiveXObject('Microsoft.XMLHTTP');
} else if(window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
}
xmlHttpReq.open('POST','http://10.2.229.82:8088/api/friend',true);
xmlHttpReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttpReq.onreadystatechange = function(){
if(xmlHttpReq.readyState === 4) {
if(xmlHttpReq.status === 200) {
alert(xmlHttpReq.responseText);
}
}
};
xmlHttpReq.send("a=1,b=2");
};
本文介绍了一种使用JavaScript实现AJAX请求的方法。包括了创建请求对象、设置请求方式、发送请求及处理响应的过程。示例代码展示了如何进行GET和POST请求,并设置请求头。
173

被折叠的 条评论
为什么被折叠?



