XMLHttpRequest 的基本用法

526 阅读1分钟

XMLHttpRequest 的基本用法

概念:XMLHttpRequest是浏览器内置的一个构造函数

作用:基于 new 出来的 XMLHttpRequest 实例对象,可以发起 Ajax 的请求。

使用XMLHttpRequest 发送ajax请求主要的 4 个实现步骤:

  1. 创建 xhr 对象
  2. 调用 xhr.open() 函数
  3. 调用 xhr.send() 函数
  4. 监听 load 事件

语法:

		//创建一个xhr对象
		  let xhr = new XMLHttpRequest()
                // 请求行, 请求方式和路径
            xhr.open('请求方式', '请求路径')
                // 请求头
                // xhr.setRequestHeader('Content-Type','值')
                // 请求体
            xhr.send(参数)
			//load事件
            xhr.addEventListener('load', function() {
                //返回的xhr.response是一个json字符串
                console.log(JSON.parse(xhr.response));
            })

1、发送get方式请求

<button>发送请求</button>
    <script>
        let btn = document.querySelector('button')
        btn.addEventListener('click', function() {
            let xhr = new XMLHttpRequest()
                // 请求行, 请求方式和路径
            xhr.open('get', '请求接口路径')
                // 请求体
            xhr.send()
            xhr.addEventListener('load', function() {
                console.log(JSON.parse(xhr.response).data);
            })
        })
    </script>

2、发送post方式请求

//给按钮绑定一个单击事件
btnadd.addEventListener('click', function() {
            let xhr = new XMLHttpRequest()
                // 请求行
            xhr.open('post', '接口路径')
                // 请求头  设置编码格式(json)
            xhr.setRequestHeader('Content-Type', 'application/json')
                // 请求体
            xhr.send(JSON.stringify({
                    bookname: bookname.value,
                    author: author.value,
                    publisher: publisher.value
                }))
                // 响应
            xhr.addEventListener('load', function() {
                console.log(JSON.parse(xhr.response));
            })
        })

请求体格式 和 对应的Content-Type值

请求体格式Content-Type是否需要在代码中指定
参数=值&参数=值application/x-www-form-urlencoded
'{ "id": 1, "name": "zs" }'application/json
new FormData()multipart/form-data; xxxxxxxxx随机字符否,浏览器自动设置