Files
ClassContent/历届学生/font-end-nine/项目练习/学生项目/冯文焌/6ajax/index.html
2024-09-27 02:06:13 +08:00

59 lines
1.7 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="">
<input type="text" name="id">
</form>
<ul>
</ul>
</body>
<script>
// 1 创建一个新的对象 举例:拿出手机
// fetch 全新的ajax请求方式 后面再用 //XHR
var ajax = new XMLHttpRequest()
//2 传入后端地址 (配置需要访问的后端地址和请求方式)举例:设置号码
ajax.open("POST","http://127.0.0.1/index.php?")
var form = new FormData();
form.append("id",1)
var params = {
id:1
}
//更改请求头类型,系统为Content-Type 更改为application 中文格式charset=UTF-8
// ajax.setRequestHeader('Content-Type','application/json,charset=UTF-8') //json格式发送后端
ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=UTF-8') //form表单格式传给后端
//3 发送请求 举例:拨号
// ajax.send(JSON.stringify(params))
ajax.send(form)
//监听请求状态
ajax.onreadystatechange = function () {
if (ajax.readyState == 4){
if (ajax.status ==200){
var data = JSON.parse(ajax.responseText)
//字符串转换为对象 JSON.parse //对象转换为字符串 JSON.stringify
console.log(data);
data.result.forEach(v => {
document.querySelector("ul").innerHTML += `<li>${v.title}</li>`
});
}else{
alert("网络请求失败")
}
}
}
</script>
</html>