大飞_dafei

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

原生 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);
  }
};
}
复制代码

 

posted on   大飞_dafei  阅读(1020)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2020-06-12 vue 中使用 Ant Design 依次提供了三级选项卡
2020-06-12 Postman中不为人知的秘密 之 设置全局变量,token
点击右上角即可分享
微信分享提示