用JavaScript写Ajax例子

来源:互联网 发布:天刀男神 太白捏脸数据 编辑:程序博客网 时间:2024/05/01 08:35

一、HTML代码如下

<input type="button" value="ajax提交" onclick="js_ajax()"><div id="resText"></div>

二、JavaScript代码如下

function js_ajax(){ //定义函数来异步获取信息// 声明一个空对象用来装入XMLHttpRequest对象var xmlHttpReq = null;// 给XMLHttpRequest对象赋值,代码如下:if(window.ActiveXObject){ //ie5 ie6是以ActiveXObject的方式引入XMLHttpRequest对象的xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");}else if(window.XMLHttpRequest){//除ie5 ie6以外的浏览器XMLHttpRequest是window的子对象xmlHttpReq = new XMLHttpRequest();//实例化一个xmlHttpRequest对象}if(xmlHttpReq != null){//如果对象实例化成功 xmlHttpReq.open("GET","001.php",true);//调用open()方法并采用异步方式xmlHttpReq.onreadystatechange=RequestCallBack; //设置回调函数xmlHttpReq.send(null);//因为使用get方式提交,所以可以使用null参调用}function RequestCallBack(){//一旦readyState值改变,将会调用这个函数if(xmlHttpReq.readyState == 4){ if(xmlHttpReq.status == 200){document.getElementById("resText").innerHTML = xmlHttpReq.responseText;}}}}

三、PHP代码如下

<?php echo "ok"; ?>


0 0
原创粉丝点击