ajax实现步骤

1. 创建 Ajax对象

​ var xhr = new XMLHttpRequest();

2. 初始化Ajax对象

​ xhr.open("get", "https://apis.netstart.cn/bcomic/Banner");

​ XMLHttpRequest.open(method,url,async)

​ method 要使用的 HTTP 方法,比如 GET、POST等

​ url 一个 DOMString 表示要向其发送请求的 URL。

​ async 可选 表示是否异步执行操作,默认为 true。

3.

发送请求

xhr.send();

XMLHttpRequest.send( [在 XHR 请求中要发送的数据体] )

如果请求是异步的(默认),那么该方法将在请求发送后立即返回。

4.

获取服务器端给与客户端响应的数据

XMLHttpRequest.readyState 只读 返回 一个无符号短整型(unsigned short)数字,代表请求的状态码。

XMLHttpRequest.onreadystatechange事件, 当 readyState 属性发生变化时,调用的 event handler。

xhr.onreadystatechange = function () {

当ajax状态码为4, 并且http状态为200的时候,我们获取服务器响应的数据

if (xhr.readyState === 4 && xhr.status == 200) {

获取服务器响应数据

获取的数据默认是字符串,将其转换成对象

var obj = JSON.parse(xhr.responseText)

最后遍历,渲染到页面上完成输出

// GET方式传递参数 通过 url?参数名1=参数值1&参数名2=参数值2...
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.example.com?uname=zhangsan&age=23&sex=男")
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
}
// POST方式传递参数  传统表单形式
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://www.example.com");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("uname=zhangsan&age=23&sex=男");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
}
// POST方式传递参数  json字符串形式
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://www.example.com");
xhr.setRequestHeader("Content-type", "application/json");
xhr.send(JSON.stringify({
uname: "zhangsan",
age: 23,
sex: "男",
}));
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值