首页 > 技术文章 > 原生JS写AJAX

xingyue1988 2017-02-17 15:12 原文

*XMLHttpRequest是Ajax的核心,通过调用XMLHttpRequest对象的属性和方法可以实现在客户端和浏览器之间进行数据的异步传输,从而实现页面的无刷新效果。

 

1.XMLHttpRequest对象的常用属性:

      onreadystatechange:指定当readyState属性值改变时的事件处理句柄(只写);

      readyState:返回当前请求的状态(只读);

      responseText:将相应信息作为字符串返回(只读);

2.XMLHttpRequest对象的常用方法:

 open():创建一个新的HTTP请求,并制定此请求的方法,URL以及验证信息(用户名/密码);

 send():发送请求到HTTP服务器并接受回应。

 3.XMLHttpRequest对象的使用需要四个步骤:

 (1) 初始化XMLHttpRequest对象

(2) 指定响应处理函数

(3) 发送HTTP请求

(4) 处理服务器返回的信息




第一步:初始化XMLHttpRequest对象,根据浏览器的不同,创建不同

if(window.XMLHttpRequest)
    {
        var xml=new XMLHttpRequest();
    }else
    {
        var xml=new ActiveXObject('Microsoft.XMLHTTP');   针对IE5/IE6浏览器
    }

 

第二步:发送HTTP请求

xml.open("传值方式POST/GET","处理界面",true);
xml.send();

       open()方法表示会建立对服务器的调用,这是初始化一个请求的纯脚本方法。

      它有2个必要的参数,还有3个可选的参数。method表示向服务器发送信息的方式,可以为Get或Post;URL表示所调用的服务器资源的URL;asynch是一个布尔值,指示这个调用时异        步还是同步,默认为true;

       send()方法具体向服务器发送请求。如果请求声明为异步的,这个方法就会立即返回,否则它会等待,知道接收到响应为止。参数content是可选的,可以是一个DOM对象的实例、一个         输入流或一个串。传入的内容会作为请求体的一部分发送。

   GET方式传值形式:

xml.open("GET","ceshichuli.php?fname=111",true);   传递的变量写到url地址
xml.send();

   POST方式传值形式:

xml.open("POST","ceshichuli.php",true);
xml.setRequestHeader("Content-type","application/x-www-form-urlencoded");  传值时,要有这一句
xml.send("fname=111");

          *如果POST方式不需要传值到处理页面的话,只写open和send即可        

xml.open("POST","ceshichuli.php",true);
xml.send();

第三步:处理服务器返回的信息

xml.onreadystatechange=function()
    {
        if(xml.readyState==4 && xml.status==200)
        {
            var str=xml.responseText;
        }
        document.getElementById("nr").innerHTML=str;    找到id元素,添加返回的数据
    }
    





readyState属性详解

    readyState属性用来表示请求的状态,有5个可取值,分别是:

      “0”:表示未初始化,即对象已经建立,但是尚未初始化(尚未调用open()方法);

      “1”:表示正在加载,此时对象已建立,尚未调用send()方法;

      “2”:表示请求已发送,即send()方法已调用;

      “3”:表示请求处理中;

      “4”:表示请求已完成,即数据接收完毕。

 

status、statusText属性详解

      status:返回当前请求的HTTP状态码(只读);

      statusText:返回当前请求的响应行状态(只读)。

 

responseText、responseXML属性详解

      responseText属性表示服务器的文本响应,其处理结果以字符串形式返回。

      responseXML属性表示服务器响应,其结果将格式化为XML Document对象。

           

 完整代码:

    if(window.XMLHttpRequest)
    {
        var xml=new XMLHttpRequest();
    }else
    {
        var xml=new ActiveXObject('Microsoft.XMLHTTP');   针对IE5/IE6浏览器
    }
    
    
    
    xml.open("POST","ceshichuli.php",true);
    
    xml.send("fname=111");
    
    
    
    
    xml.onreadystatechange=function()
    {
        if(xml.readyState==4 && xml.status==200)
        {
            var str=xml.responseText;
        }
        document.getElementById("nr").innerHTML=str;
    }
    

 js封装的ajax方法,进行简单的返回数据验证

前端页面代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style>

</style>
</head>

<body>
<div><input type="text" id="uid"/></div>
<div><input type="text" id="pwd"/></div>
<div><input type="button" value="登录" id="denglu"/></div>
</body>
</html>
<!--/* 封装ajax函数
 * @param {string}aa.type http连接的方式,包括POST和GET两种方式
 * @param {string}aa.url 发送请求的url
 * @param {boolean}aa.async 是否为异步请求,true为异步的,false为同步的
 * @param {object}aa.data 发送的参数,格式为对象类型
 * @param {string}aa.datatype 定义返回类型
 * @param {function}aa.success ajax发送并接收成功调用的回调函数
 */-->
<script>
window.onload=function()
{
        var dl=document.getElementById("denglu");
        dl.onclick=function()
        {
        var uid=document.getElementById("uid").value;
        var pwd=document.getElementById("pwd").value;
            ajax({
                    method: 'POST',
                    url: 'login.php',
                    dataType:"TEXT",
                    data: {
                        uid: uid,
                        pwd: pwd
                    },
                    success: function (data) {
                       alert(data);
                    }
             });
        }
}




    function ajax(aa) {
        aa = aa || {};
        aa.method = aa.method.toUpperCase() || 'POST';
        aa.url = aa.url || '';
        aa.async = aa.async === false ? false : true;
        aa.data = aa.data || null;
        aa.dataType = (aa.dataType || 'TEXT').toUpperCase();
        aa.success = aa.success || function () {};
        var xmlHttp = null;
        if (XMLHttpRequest) {
            xmlHttp = new XMLHttpRequest();
        }
        else {
            xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
        }
        var params = [];
        for (var key in aa.data){
            params.push(key + '=' + aa.data[key]);
        }
        var postData = params.join('&');
        if (aa.method.toUpperCase() === 'POST') {
            xmlHttp.open(aa.method, aa.url, aa.async);
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
            xmlHttp.send(postData);
        }
        else if (aa.method.toUpperCase() === 'GET') {
            xmlHttp.open(aa.method, aa.url + '?' + postData, aa.async);
            xmlHttp.send(null);
        } 
        xmlHttp.onreadystatechange = function () {
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                if(aa.dataType == 'JSON') {
 
                aa.success(JSON.parse(xmlHttp.responseText));
            } else {
 
                aa.success(xmlHttp.responseText);
 
            }
            }
        };
    }
    </script>
View Code

处理界面代码

<?php
$uid=$_POST['uid'];
$pwd=$_POST['pwd'];
if($uid=="" || $pwd=="")
{
    echo "用户名或密码不能有空";
    }
    else
    {
        $db=new MySQLi('localhost','root','123','test1');
        mysqli_connect_error()?"链接失败":"";
        $sql="select pwd from lc_user where uid='{$uid}'";
        $result=$db->query($sql);
        $attr=$result->fetch_all();
        if($attr[0][0]==$pwd)
        {
            echo "登录成功";
            }else
            {
                echo "用户名或密码输入不正确";
                };
        }
View Code

 

推荐阅读