原生 JavaScript发送GET 、POST请求方法
原生 JavaScript发送GET 、POST请求方法
<p><button onclick="fooGet()">GET 请求 大飞</button> </p> <p>22222</p> <p>22222</p> <p>22222</p> <button onclick="fooPost()">POST 请求 DaFei</button>
GET请求
// get 请求接口 function fooGet() { let url = "http://www.dafei.com/api/testGet.php?name=dafei" //第一步:建立所需的对象 let httpRequest = new XMLHttpRequest(); //第二步:打开连接 将请求参数写在url中 httpRequest.open('GET', url, true); //第三步:发送请求 将请求参数写在URL中 httpRequest.send(); httpRequest.onreadystatechange = function () { if (httpRequest.readyState === 4 && httpRequest.status === 200) { alert("get接口请求成功 ok") var json = httpRequest.responseText; //获取到json字符串,还需解析 console.log(json); } }; }
// post 请求接口 function fooPost() { let url = "http://www.dafei.com/api/testPost.php" //第一步:创建需要的对象 var httpRequest = new XMLHttpRequest(); //第二步:打开连接 /***发送json格式文件必须设置请求头 ;如下 - */ httpRequest.open('POST', url, true); //设置请求头 注:post方式必须设置请求头(在建立连接后设置请求头) httpRequest.setRequestHeader("Content-type", "application/json"); const obj = { foo: "123", bar: "456", name: "dafei" } httpRequest.send(JSON.stringify(obj)); //发送请求 将json写入send中sss httpRequest.onreadystatechange = function () {//请求后的回调接口,可将请求成功后要执行的程序写在其中 if (httpRequest.readyState === 4 && httpRequest.status === 200) {//验证请求是否发送成功 alert("post接口请求成功 ok") var json = httpRequest.responseText;//获取到服务端返回的数据 console.log(json); } }; }
分类:
JavaScript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
2020-06-12 vue 中使用 Ant Design 依次提供了三级选项卡
2020-06-12 Postman中不为人知的秘密 之 设置全局变量,token