打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
原生ajax发送数据,以及不用的方法发送

原生js发送ajax请求

4步:

//1. 实例化xhr对象var xhr = new XMLHttpRequest();//2. 调用open方法准备ajax请求//参数1: 请求方式 (get、post、delete、put)//参数2: 请求的服务器端的地址//参数3: true(异步、默认)、false(同步)xhr.open('get', '/getData');//3. 调用send方法发送ajax请求xhr.send();//4. 调用onload事件,配合responseText来接收服务器端返回的数据// xhr.responseText: 以字符串形式来接收服务器端返回的结果// 服务器端返回的数据有两种可能://  1) 普通字符串(hello world \ I am xiaoming)//  2) json字符串('{"id":"101", type:"goods", "name":"小米"}')//     json字符串都会使用 JSON.parse 转回成对象形式xhr.onload = function () {    xhr.responseText}

发送请求时get传参

get参数要拼接在url地址的后面,以?进行分割

var xhr = new XMLHttpRequest();//参数2的位置用来拼接get参数, 以 ? 作为分隔符// ?之前: 请求的url地址// ?之后: 查询参数 key1=value1&key2=value2&...xhr.open('get', '/getData?id=1&name=zs&age=20&...');xhr.send();xhr.onload = function () {    xhr.responseText}

发送请求时post传参

post传参有三种方式: key=value&key=value&... FormData json字符串

//1. key=value&key=value&...// application/x-www-form-urlencoded : 需要key=value这种结构的参数var xhr = new XMLHttpRequest();xhr.open('post', '/postData');//将发送到服务器端的数据写成一个字符串var str = 'id=1&name=zs&age=20&...'//发送请求之前一定要设置请求头为 application/x-www-form-urlencodedxhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');xhr.send(str);xhr.onload = function () {    xhr.responseText}
//2. 发送FormData类型的数据//1) 直接获取整个post表单的数据var fm = document.querySelector('form');var fd = new FormData(fm)//2) 实例化一个空的FormData,再向里面append数据var fd = new FormData();fd.append('name', 'xiaoming');fd.append('age', 20);fd.append('img', this.files[0]);//发送ajax请求时,如果发送到服务器端的数据为FormData时,不需要设置请求头,需要将fd作为参数传入sendvar xhr = new XMLHttpRequest();xhr.open('post', '/postData');xhr.send(fd);xhr.onload = function () {    xhr.responseText}
//3. 发送到服务器端的数据是json字符串var jsonStr = JSON.stringify({name:"zs", age:20});  //'{name:"zs", age:20}'var xhr = new XMLHttpRequest();xhr.open('post', '/postData');xhr.setRequestHeader('content-type', 'application/json');xhr.send(jsonStr);xhr.onload = function () {    xhr.responseText}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Ajax第一阶段学习
Ajax總結篇
原生JavaScript手写Ajax
JavaScript中的AJAX
Javascript 内置方法之 XMLHttpRequest
WEB前端第六十课——原生Ajax与HTTP协议
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服