使用ajax原生代码向服务器后端请求或发送数据的方法

ajax使用步骤:

  1.给后端发请求

  2.服务端返回数据

  3.根据服务端返回的数据,做相应的操作

首先,我们实例化一个XHR对象,代表我要使用AJAX技术。

var xhr = new XMLHttpRequest();

然后向服务器发送请求,以下是两种发送请求的方法(“GET"和"POST”)

xhr.open('GET', 'http://www.baidu.com', true)
xhr.open('POST', 'http://www.baidu.com', true)

如果你是用"POST"方法发送的请求的话,就必须向服务器发送一个叫“Content-Type”的请求头(Request Header) 用以指明请求数据的类型,除了Content-Type之外,它还可以向服务器发送其它一些Headers(请求头)。
比如:

//如果是向服务器发送的是json格式
xhr.setRequestHeader("Content-type","application/json");
//如果是发送的是urlencoded格式
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

然后向服务器发送数据:

xhr.send();//如果你只是请求数据的话,括号里面就不用填写

然后你要了解XHR对象有3个重要的属性,分别是

1.onreadystatechange //此事件是在readyState属性发生改变时触发的,readyState属性每改变一次,此事件就会触发一次

2.readyState //此值为4的时候表示向服务器请求成功

3.status //此值为200的时候表示已经得到数据

xhr.onreadystatechange = function () 
{
	if (xhr.readyState === 4) 
	{
       if (xhr.status === 200)
        {
	       //成功地时候做的事
           alert(xhr.responseText);
        } 
        else 
        {
	      //失败的时候做的事
          alert('There was a problem with the request.');
        }
    }
}

然后我写一个完整的参考代码:

(function () {
        var but = document.getElementById("ajaxButton");
        but.addEventListener("click", makeRequest);

        function makeRequest() {
            httpRequest = new XMLHttpRequest();
            if (!httpRequest) {
                alert("创建请求失败");
            }
            httpRequest.open("GET", "test.json");//这里我是请求的本地的一个json文件
            httpRequest.send();//没有向后端发送数据
            httpRequest.onreadystatechange = function () {
                if (httpRequest.readyState === 4) {
                    if (httpRequest.status === 200) {
                        var data = JSON.parse(httpRequest.responseText);
                        but.innerText = data.student.name;
                    }
                    else {
                        alert(There was a problem with the request.);
                    }
                }
            }
        }
    })();

补充:各个状态下readyState的值

<script>

    var xhr = new XMLHttpRequest()
    console.log(xhr.readyState)
    // => 0
    // 初始化 请求代理对象

    xhr.open('GET', 'time.php')
    console.log(xhr.readyState)
    // => 1
    // open 方法已经调用,建立一个与服务端特定端口的连接

    xhr.send()

    xhr.addEventListener('readystatechange', function () {
      switch (this.readyState) {
        case 2:
          // => 2
          // 已经接受到了响应报文的响应头

          // 可以拿到头
          console.log(this.getAllResponseHeaders())
          // 但是还没有拿到体
          console.log(this.responseText)
          break;

        case 3:
          // => 3
          // 正在下载响应报文的响应体,有可能响应体为空,也有可能不完整
          // 在这里处理响应体不保险(不可靠)
          console.log(this.responseText)
          break;

        case 4:
          // => 4
          //整个响应报文已经完整下载下来了
          console.log(this.responseText)
          break;
      }
    })

  </script>

不懂的可以在下方留言,看到后会回复

  • 6
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值