Ajax中的JSON
构建JSON格式数据
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ajax中的JSON</title>
</head>
<body>
<button id="btn">请求</button>
<script src="js/createXMLHttpRequest.js"></script>
<script>
var btn = document.getElementById("btn");
btn.addEventListener("click", function () {
var xhr = createXMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// 1. 接收数据 - JSON数据格式,是字符串类型
var data = xhr.responseText;
// 2. 将符合JSON格式的字符串类型数据进行转换
var json = JSON.parse(data);
// 3. 进行具体处理
console.log(json);
}
};
xhr.open("post", "server.json");
xhr.setRequestHeader(
"Content-Type",
"application/x-www-form-urlencoded"
);
var obj = {
name: "周芷若",
age: 18,
};
xhr.send("name=" + obj.name + "&age=" + obj.age);
});
</script>
</body>
</html>
返回结果如下
接收JSON格式数据
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ajax中的JSON</title>
</head>
<body>
<button id="btn">请求</button>
<script src="js/createXMLHttpRequest.js"></script>
<script>
var btn = document.getElementById("btn");
btn.addEventListener("click", function () {
var xhr = createXMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// 1. 接收数据 - JSON数据格式,是字符串类型
var data = xhr.responseText;
// 2. 将符合JSON格式的字符串类型数据进行转换
var json = JSON.parse(data);
// 3. 进行具体处理
console.log(json);
}
};
xhr.open("get", "server.json");
xhr.send(null);
});
</script>
</body>
</html>
补充 XML
xml文件
<?xml version="1.0" encoding="utf-8" ?>
<body>
<name>张无忌</name>
</body>
Ajax中的XML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ajax中的XML</title>
</head>
<body>
<button id="btn">请求</button>
<script src="js/createXMLHttpRequest.js"></script>
<script>
var btn = document.getElementById("btn");
btn.addEventListener("click", function () {
var xhr = createXMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// 1. 接收数据 - responseXML属性 -> 接收XML数据格式
var data = xhr.responseXML;
// 2. 利用DOM解析XML即可
var nameElement = data.getElementsByTagName("name")[0];
console.log(nameElement.textContent); // 张无忌
}
};
xhr.open("get", "server.xml");
xhr.send(null);
});
</script>
</body>
</html>