原生ajax请求的五个步骤(ajax请求步骤详细代码案例)
要问什么是ajax?通俗的讲就是在网页中利用XMLHttpRequest对象和服务器进行数据交互的方式,就是Ajax。本文聊一聊原生ajax请求的五个步骤,一个ajax请求步骤详细代码案例,使用xhr发起POST请求,一个非常简单的案例希望助你学习好ajax请求知识。
步骤1. 创建 xhr 对象
1 | var xhr = new XMLHttpRequest() |
步骤2. 调用 open()
1 | xhr.open( 'POST' , 'http://www.xxxxx.com:3359/api/addbook' ) |
步骤 3. 设置 Content-Type 属性(固定写法)
1 | xhr.setRequestHeader( 'Content-Type' , 'application/x-www-form-urlencoded' ) |
步骤4. 调用 send(),同时将数据以查询字符串的形式,提交给服务器
1 | xhr.send( 'bookname=水浒传&author=施耐庵&publisher=天津图书出版社' ) |
步骤5. 监听 onreadystatechange 事件
1 2 3 4 5 | xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText) } } |
完整的ajax请求步骤详细案例代码:
1 2 3 4 5 6 7 8 9 | var xhr = new XMLHttpRequest() xhr.open( 'POST' , 'http://www.xxxxx.com:3359/api/addbook' ) xhr.setRequestHeader( 'Content-Type' , 'application/x-www-form-urlencoded' ) xhr.send( 'bookname=水浒传&author=施耐庵&publisher=天津图书出版社' ) xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText) } } |
智能机器人
除注明外的文章,均为来源:老汤博客,转载请保留本文地址!
原文地址:https://tangjiusheng.cn/ajax/298.html
原文地址:https://tangjiusheng.cn/ajax/298.html