ajax怎么写

Ajax

1个回答

写回答

涂涂xiu@

2022-06-19 15:49

+ 关注

Ajax
Ajax

Ajax的写法可以分为以下五步:

1.创建 XMLHttpRequest对象

XML
XML

var xhr = new XMLHttpRequest();

2.设置请求参数

xhr.open('GET', 'url');

xhr.setRequestHeader('Content-Type', 'application/JSon');

3.发送请求

xhr.send();

4.响应处理

xhr.onreadystatechange = function () {

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

console.log(xhr.responseText);

}

}

5.错误处理

xhr.onerror = function () {

console.log('请求出错!');

}

示例:

var xhr = new XMLHttpRequest();

xhr.open('GET', 'https://api.example.com/data.JSon', true);

xhr.setRequestHeader('Content-Type', 'application/JSon');

xhr.send();

xhr.onreadystatechange = function () {

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

console.log(xhr.responseText);

}

}

xhr.onerror = function () {

console.log('请求出错!');

}

举报有用(17分享收藏

Copyright © 2025 IZhiDa.com All Rights Reserved.

知答 版权所有 粤ICP备2023042255号