js 实现ajax发送

js发送ajax发送,分步骤进行

ajax的核心 是XMLHttpRequest,

步骤1:创建一个对象xmlrequest,在主流的浏览器都支持new ,

var xmlhttp = new XMLHttpRequest()  IE浏览器不支持这种方法,需要再写一个函数来创建

步骤2 :连接服务端

得到XMLHTTPRequest对象后,就可以调用对象的open()方法,与服务器连接,参数如下

open(method,url,async):

  method:请求方法GET或POST,

  url:服务器的地址,

  async :表示异步请求,可以不写,默认是True,

xmlhttp.open("GET“,"/ajax_get/",true);

步骤3:发送请求

xmlhtto.send(null),有兼容的问题,加上null, null在js中一种数据类型,表示空,

 

以上3个步骤相当于jquery的

$.ajax({

  url:"/ajax_get/",

  type:"GET",

  success:function(){

  

  }

  )}

 

 

步骤4:接收服务器响应,

请求发出,服务端开始执行,

XMLHttpRequest对象有一个onreadystatechange事件,

0:初始化外网状态,只创建XMLHttpRequest对象,

1:请求开始,open( )方法调用,

2:请求发送完成状态,send()方法调用,

3: 开始读取服务器响应,

4:读取服务器响应结束,

onreadystatechange 事件会在状态为1,2,3,4 时引发,

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>

<form action="/index/" method="post">

    <p><input type="text">{{ error }}</p>
    <p><input type="text">{{ error }}</p>
    <p><input type="submit"></p>

</form>

<p>用户名:<input type="text" class="user"></p>
<button onclick="send()">ajax</button>

</body>

<script>
{#    给button按钮绑定send事件#}
    function send() {

        var ele = document.getElementsByClassName("user")[0];
        var con = ele.valueOf;

        xmlHttp=new XMLHttpRequest();
        xmlHttp.open("GET","/getajax/",true);
        xmlHttp.send(null);

        {#监听服务端 #}
        xmlHttp.onreadystatechange=function () {
            if (xmlHttp.readyState ==4 && xmlHttp.status ==200){
                alert(xmlHttp.responseText);
                alert(typeof xmlHttp.responseText)

            }
        }

 }
通过XMLHttpRequest对象的readyState属性来得到XMLHttpRequest对象的状态。
需要获取到服务器响应的内容,可以通过XMLHttpRequest对象的responseText得到服务器响应内容。
</script> </html>

ajax的post请求

<1>需要设置请求头:xmlHttp.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”)注意 :form表单会默认这个键值对不设定,Web服务器会忽略请求体的内容。

<2>在发送时可以指定请求体了:xmlHttp.send(“username=yuan&password=123”)

 

    创建XMLHttpRequest对象;
    调用open()方法打开与服务器的连接;
    调用send()方法发送请求;
    为XMLHttpRequest对象指定onreadystatechange事件函数,这个函数会在

    XMLHttpRequest的1、2、3、4,四种状态时被调用;

    XMLHttpRequest对象的5种状态,通常我们只关心4状态。

    XMLHttpRequest对象的status属性表示服务器状态码,它只有在readyState为4时才能获取到。

    XMLHttpRequest对象的responseText属性表示服务器响应内容,它只有在
    readyState为4时才能获取到!

 

posted @ 2017-12-03 14:56  谷子的  阅读(23481)  评论(0编辑  收藏  举报