网站域名在哪里注册,新手学建设网站书籍,做公众好号的网站,网站建设qinnet目录 一、介绍1.创建 XMLHttpRequest2.初始化3.发送请求4.获取响应5.响应类型 二、发送GET请求示例三、发送POST请求示例四、发送POST请求下载文件示例五、发送POST请求上传文件示例 一、介绍
1.创建 XMLHttpRequest
let xhr new XMLHttpRequest();2.初始化
xhr.open(metho… 目录 一、介绍1.创建 XMLHttpRequest2.初始化3.发送请求4.获取响应5.响应类型 二、发送GET请求示例三、发送POST请求示例四、发送POST请求下载文件示例五、发送POST请求上传文件示例 一、介绍
1.创建 XMLHttpRequest
let xhr new XMLHttpRequest();2.初始化
xhr.open(method, URL, [async, user, password])使用 open 方法进行一些初始化配置method 和 URL 是必传的其余的是可选的。
参数说明
method —— HTTP 方法。通常是 “GET” 或 “POST”小写也可。 URL —— 要请求的 URL通常是一个字符串也可以是 URL 对象。 async —— 是否同步。如果不传默认为true如果显式地设置为 false那么请求将会以同步的方式处理。 userpassword —— HTTP 基本身份验证如果需要的话的登录名和密码。
3.发送请求
xhr.send([body])使用 send 方法就会建立连接发送请求。
参数说明
body 是可选的是 POST 请求方式的请求体。 即如果你上面的 xhr.open 里 method 是 使用的是 GET 请求 那么 body 参数是不需要的 如果你上面的 xhr.open 里 method 是 使用的是 POST 请求那么请求体就是 body 。
4.获取响应
下面这三个事件是最常用的
load —— 当请求完成即使 HTTP 状态为 400 或 500 等并且响应已完全下载。error —— 当无法发出请求例如网络中断或者无效的 URL。progress —— 在下载响应期间定期触发报告已经下载了多少。
xhr.onload function() { //请求正常发出时alert(状态码: ${xhr.status} 结果 ${xhr.response});
};xhr.onerror function() { // 仅在根本无法发出请求时触发alert(网络错误);
};xhr.onprogress function(event) { // 定期触发一般用于下载文件之类的返回下载进度// event.loaded —— 已经下载了多少字节// event.lengthComputable true当服务器发送了 Content-Length header 时// event.total —— 总字节数如果 lengthComputable 为 truealert(总字节数 ${event.total} 已下载字节数 ${event.loaded} );
};5.响应类型
我们可以使用 xhr.responseType 属性来设置响应格式
“”默认—— 响应格式为字符串“text” —— 响应格式为字符串“arraybuffer” —— 响应格式为 ArrayBuffer对于二进制数据请参见 ArrayBuffer二进制数组“blob” —— 响应格式为 Blob对于二进制数据请参见 Blob即文件数据“document” —— 响应格式为 XML document可以使用 XPath 和其他 XML 方法或 HTML document基于接收数据的 MIME 类型“json” —— 响应格式为 JSON自动解析
let xhr new XMLHttpRequest();xhr.open(GET, /article/xmlhttprequest/example/json);xhr.responseType json;xhr.send();// 响应为 {message: Hello, world!}
xhr.onload function() {let responseObj xhr.response;alert(responseObj.message); // Hello, world!
}; 注意 在旧的脚本中你可能会看到 xhr.responseText甚至会看到 xhr.responseXML 属性。 它们是由于历史原因而存在的以获取字符串或 XML 文档。如今我们应该在 xhr.responseType 中设置格式然后就能获取如上所示的 xhr.response 了。 二、发送GET请求示例
let xhr new XMLHttpRequest();
xhr.open(GET, http://localhost:8081/apiList/v1/worldAddressAnalysis?country中国);
xhr.send();//请求正常发出时
xhr.onload function () { alert(状态码: ${xhr.status} 结果 ${xhr.response});
};// 仅在根本无法发出请求时触发
xhr.onerror function () { alert(网络错误);
};三、发送POST请求示例
let xhr new XMLHttpRequest();
xhr.open(POST, http://localhost:8081/apiList/v1/calculator);
xhr.setRequestHeader(Content-Type, application/json; charsetutf-8);//post 请求体参数
let param {calculatorStr: 8*8-4};
xhr.send(JSON.stringify(param));//请求正常发出时
xhr.onload function () { alert(状态码: ${xhr.status} 结果 ${xhr.response});
};// 仅在根本无法发出请求时触发
xhr.onerror function () { alert(网络错误);
};四、发送POST请求下载文件示例
!DOCTYPE html
html langenheadmeta charsetUTF-8titleDocument/title
/headbodybutton idbtn下载文件/buttonscriptlet btn document.querySelector(#btn);btn.addEventListener(click, () {let xhr new XMLHttpRequest();xhr.open(POST, http://localhost:8081/apiList/v1/downloadExcel);//设置请求头和响应类型xhr.setRequestHeader(Content-Type, application/json;charsetUTF-8); xhr.responseType blob;//设置请求体参数let param { fileName: 测试, tableHeader: [年级, 班级, 班主任, 男生人数, 女生人数, 语文平均分] };xhr.send(JSON.stringify(param));//请求正常发出时xhr.onload function () { if (xhr.status 200) {// 获取文件blob数据并保存saveAs(xhr.response, download.xlsx);}};// 仅在根本无法发出请求时触发xhr.onerror function () { alert(网络错误);};// 定期触发 查看下载进度xhr.onprogress function (event) { alert(总字节数 ${event.total} 已下载字节数 ${event.loaded} );};});function saveAs(data, name) {var urlObject window.URL || window.webkitURL || window;var export_blob new Blob([data]);var save_link document.createElementNS(http://www.w3.org/1999/xhtml, a)save_link.href urlObject.createObjectURL(export_blob);save_link.download name;save_link.click();}/script
/body/html五、发送POST请求上传文件示例
假设我 springboot 上传文件的接口如下: ApiOperation(文件上传到jar包所在服务器)PostMapping(value /v1/fileSelfUpload1, consumes MediaType.MULTIPART_FORM_DATA_VALUE)public JSONObject fileSelfUpload1(RequestParam String filePath, RequestParam(value file, required true) MultipartFile file) {return userConsumer.fileSelfUpload(filePath, file);}使用 XMLHttpRequest 上传文件示例如下
!DOCTYPE html
html langen-usheadmeta charsetutf-8meta nameviewport contentwidthdevice-width, initial-scale1.0titleShopping list example/titlestyleli {margin-bottom: 10px;}li button {font-size: 8px;margin-left: 20px;color: #666;}/style
/headbodydiv classcontainerinput typefile namedoc iddocbutton typesubmit idsubmit提交/button/divscriptvar doc document.querySelector(#doc)var subbtn document.querySelector(#submit)subbtn.addEventListener(click, function (e) {// 获取上传的文件,数组let filedata doc.files//先判断是否已经上传文件if (filedata.length 0) {return alert(请上传文件)}//通过FormData可以获取表单数据也可以通过append添加数据最后把FormData实例对象直接 上传发送请求let fd new FormData()fd.append(file, filedata[0])fd.append(filePath, /user/save/)const xhr new XMLHttpRequest()xhr.open(POST, http://localhost:8081/apiList/v1/fileSelfUpload1)xhr.send(fd)xhr.onreadystatechange function () {if (xhr.readyState 4 xhr.status 200) {console.log(上传成功);}}})/script
/body/html参考
XMLHttpRequest
XMLHttpRequest api