POST 请求:
发送的参数格式不同, 请求头设置不同, 具体参照 Http 请求中请求头 Content-Type 讲解
发送的参数格式不同, 后台获取方式也不相同 PHP 请看 PHP 获取 POST 数据的三种方法 https://www.cnblogs.com/Im-Victor/p/9408982.html
一, 使用 XMLHttpRequest
主要分三步:
第一步: 创建需要的对象, 这里主要用到的是 XMLHttpRequest, 注意需要考虑早期的 IE;
第二步: 连接和发送;
第三步: 接收;
GET 请求:
- var httpRequest = new XMLHttpRequest();// 第一步: 建立所需的对象
- httpRequest.open('GET', 'url', true);// 第二步: 打开连接 将请求参数写在 url 中 ps:"./Ptest.php?name=test&nameone=testone"
- httpRequest.send();// 第三步: 发送请求 将请求参数写在 URL 中
- /**
- * 获取数据后的处理程序
- */
- httpRequest.onreadystatechange = function () {
- if (httpRequest.readyState == 4 && httpRequest.status == 200) {
- var JSON = httpRequest.responseText;// 获取到 JSON 字符串, 还需解析
- console.log(JSON);
- }
- };
post 方式发送 JSON
- var httpRequest = new XMLHttpRequest();// 第一步: 创建需要的对象
- httpRequest.open('POST', 'https:// 你的地址', true); // 第二步: 打开连接 /*** 发送 JSON 格式文件必须设置请求头 ; 如下 - */
- httpRequest.setRequestHeader("Content-type", "application/json");// 设置请求头 注: post 方式必须设置请求头 (在建立连接后设置请求头)var obj = { name: 'zhansgan', age: 18 };
- const obj = {
- }
- httpRequest.send(JSON.stringify(obj));// 发送请求 将 JSON 写入 send 中
- /**
- * 获取数据后的处理程序
- */
- httpRequest.onreadystatechange = function () {// 请求后的回调接口, 可将请求成功后要执行的程序写在其中
- if (httpRequest.readyState == 4 && httpRequest.status == 200) {// 验证请求是否发送成功
- var JSON = httpRequest.responseText;// 获取到服务端返回的数据
- console.log(JSON);
- }
- };
来源: http://www.bubuko.com/infodetail-3299339.html