原生JS实现Ajax的GET POST请求

来源:互联网 发布:百度人口迁徙数据 编辑:程序博客网 时间:2024/05/22 11:35

传统方法的的缺陷

传统的web交互是用户触发一个http请求服务器,然后服务器收到之后,在做出响应到用户,并且返回一个新的页面,,每当服务器处理客户端提交的请求时,客户都只能空闲等待,并且哪怕只是一次很小的交互、只需从服务器端得到很简单的一个数据,都要返回一个完整的HTML页,而用户每次都要浪费时间和带宽去重新读取整个页面。这个做法浪费了许多带宽,由于每次应用的交互都需要向服务器发送请求,应用的响应时间就依赖于服务器的响应时间。这导致了用户界面的响应比本地应用慢得多。

Ajax出现

ajax的出现,刚好解决了传统方法的缺陷。AJAX 是一种用于创建快速动态网页的技术。通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。

Get请求

<!DOCTYPE html><html>    <head>        <meta charset="UTF-8">        <title></title>    </head>    <body>        <div id="showInfo"></div>        <form id="form">            用户名:<input type="text" name="username" id="username"/><br />            密码:<input type="password" name="password" id="passowrd" />            <input type="button" value="提交" id="btn" />        </form>        <script type="text/javascript">            window.onload=function(){                var btn=document.getElementById("btn");                btn.onclick=function(){                var username=document.getElementById("username").value;                var password=document.getElementById("passowrd").value;                var xhr=null;                if(window.XMLHttpRequest){                    xhr=new XMLHttpRequest();                }else{                    xhr=new ActiveXObject('Microsoft.XMLHTTP');                }                var url='new_file.php?username='+username+'&password='+password;                xhr.open('get',url,true);                xhr.onreadystatechange=function(){                    if(xhr.readyState==4){                        if(xhr.status==200){                            var data=xhr.responseText;                            if(data==1){                                document.getElementById("showInfo").innerHTML='提交失败';                            }else if(data==2){                                document.getElementById("showInfo").innerHTML='提交成功后';                            }                        }                    }                }                    xhr.send(null);                }            }        </script>    </body></html>

Post请求

这里写图片描述

new_file.php

<?php //$username = $_GET['username'];//$password = $_GET['password'];$username=$_POST['username'];$password=$_POST['password'];if($username == 'admin' && $password == '123'){    echo 2;}else{    echo 1;}?>

注意:
ajax请求是异步请求,所以open的第三个参数应该设置为ture,可是我试过在get请求的时候,false,也就是设置为同步请求,仍然不会报错,但是还是推荐设置为true:进行异步请求。

原创粉丝点击