• Ajax的简单实现


    HTML部分:

    <body>
    <input type="button" value="Ajax提交" onclick="Ajax();" />
    <div id="resText" ></div>
    </body>

    这里有个input按钮,点击会触发click事件,click事件调用Ajax()方法。

    JS部分:

    <script language="javascript" type="text/javascript">
    //通过这个函数来异步获取信息
    function Ajax(){ 
        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","test.php",true);    //调用open()方法并采用异步方式
            xmlHttpReq.onreadystatechange=RequestCallBack; //设置回调函数
            xmlHttpReq.send(null);    //因为使用get方式提交,所以可以使用null参调用
        }
        function RequestCallBack(){//一旦readyState值改变,将会调用这个函数
            if(xmlHttpReq.readyState == 4){
                    if(xmlHttpReq.status == 200){
                        //将xmlHttpReq.responseText的值赋给ID为 resText 的元素
                        document.getElementById("resText").innerHTML = xmlHttpReq.responseText;
                    }
            }
        }
    }
    </script>

    Ajax大约分四步,创建Ajax对象,用open()方法偷偷的跑到服务器去获取数据,成功后做相应的处理。用GET方法将要提交的参数写到open方法的url参数中就行了,此时send方法的参数为null。

    例如GET方法 :
    var url = "login.php?user=XXX&pwd=XXX";
    xmlHttpRequest.open("GET",url,true);
    xmlHttpRequset.send(null);

    例如POST方法:
    xmlHttpRequest.open("POST","login.php",true);
    xmlHttpRequest.setRequestHeder("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
    xmlHttpRequest.send("user="+username+"&pwd="+password);

    如果需要在send里传递参数则setRequestHeder是必须的
    需要注意的是根据提交方式的不同,两种提交方式分别调用后台的doGet方法和doPost方法处理。

    PHP部分:

    <?php
       echo "Hello Ajax!";
    ?>

    Ajax获取了PHP的数据后,就会偷偷的将数据放到相应的div层中。这个click事件并没有使得页面刷新,就偷偷的获取了服务器端的数据,服务端的数据也可以是从数据库里读取出来的,获取数据后,Ajax还可以进行一些动作的处理。

    一切都在悄无声息中。

  • 相关阅读:
    试图加载格式不正确的程序。 (异常来自 HRESULT:0x8007000B)
    git 撤销刚提交的 commint
    At least one cache should be provided per cache operation.
    @Primary注解
    怎么把sql server数据导入mysql本地数据库?
    应用程序已预编译,因此不允许使用目录“/App_Code/”
    SpringBoot学习笔记15——Dozer的使用用来两个对象之间属性转换的工具
    Invalid packaging for parent POM (pom.xml), must be "pom" but is "jar" @ pom.xml
    浏览器调试console的多种用法
    bug本天成,妙手偶得之。
  • 原文地址:https://www.cnblogs.com/jiqing9006/p/2716385.html
Copyright © 2020-2023  润新知