首页 > 应用开发 > IT综合 > h5~js~ajax(15)
先上传源代码
if(window.XMLHttpRequest) {
//IE7, Firefox, Opera支持
req = new XMLHttpRequest();
}else if(window.ActiveXObject) {
//IE5,IE6支持
req = new ActiveXObject("Microsoft.XMLHTTP");
}
第一步根据不同的内核初始化request对象
req.open("GET", url, true);
第二步 调用XMLHttpRequest对象函数open()准备向servlet发送请求(此时只是“准备发送”,并没有发送)
第一个参数为请求方法,参数二为请求地址
参数三为同步或者异步请求
req.send(null);
第三真正的发送请求
req.onreadystatechange = callback;
第四 回调函数调用一个触发事件onreadystatechange,每当 readyState 改变时,onreadystatechange 函数就会被执行。readyState有5个可能值:0:请求未初始化(在调用open()之前);1:请求已经提出(调用send()之前);2:请求已经发送(这里通常可以从响应得到内容头部);3:请求处理中(响应中通常有部分数据可用,但是服务器还没有完成响应);4:请求已经完成(可以访问服务器响应并使用它)
var check = req.responseText;
第五 XMLHttpRequest.status = 200表示服务器已经成功响应。 定义一个变量接受后端的返回数据reponseText
注意:chrom 浏览器不支持本地的ajax请求 当使用localhost+链接地址 status的返回值为0而不是200,相同的代码在其他浏览器没有问题,所以在chrom上测试ajax请求 应该使用ip地址而不是localhost
:
<html>
<head>
<meta charset="utf-8">
<title>AJAX</title>
</head>
<body>
手机号 :<input type="text" id="mobile"><br>
<input id="bt01" type="button" value="查询">
<script>
var xmlHttp;
function geturl()
{
//创建请求对象
createXMLHttpRequest();
//发送请求
/* var url="http://www.h5edu.cn/Public/weixin/test01.php";*/
var url="abc.txt";
var param="tel="+document.getElementById("mobile").value;
send(url,"get",param);
//调用回调函数处理返回结果
}
function createXMLHttpRequest()
{
if(window.ActiveXObject)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}else{
xmlHttp=new XMLHttpRequest();
}
}
function send(url,method,param)
{xmlHttp.open(method,url,true);
xmlHttp.onreadystatechange=callback;
xmlHttp.send(param);
}
function callback()
{
var result;
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
result=xmlHttp.responseText;
alert(result);
}
}
}
document.getElementById("bt01").onclick=geturl;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ajax基础</title>
</head>
<body>
点击按钮的时候,读取abc.txt<input id="btn" type="button" value="读取"/><br/>
<div id="con"></div>
</body>
</html>
<script type="text/javascript" src="../js/ajax.js"></script>
<script type="text/javascript">
window.onload = function(){
var oBtn = document.getElementById('btn');
var oCon = document.getElementById('con');
oBtn.onclick = function(){
ajax('abc.txt',function(str){
oCon.innerHTML = str;
});
}
}
</script>
</body>
</html>
ajax.js
function ajax(url, fnSucc, fnFaild){
//1.创建对象
var oAjax = null;
if(window.XMLHttpRequest){
oAjax = new XMLHttpRequest();
}else{
oAjax = new ActiveXObject("Microsoft.XMLHTTP");
}
//2.连接服务器
oAjax.open('GET', url, true); //open(方法, url, 是否异步)
//3.发送请求
oAjax.send();
//4.接收返回
oAjax.onreadystatechange = function(){ //OnReadyStateChange事件
if(oAjax.readyState == 4){ //4为完成
if(oAjax.status == 200){ //200为成功
fnSucc(oAjax.responseText)
}else{
if(fnFaild){
fnFaild();
}
}
}
};
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/30545764/viewspace-2120994/ ,如需转载,请注明出处,否则将追究法律责任。