大概入了JavaScript的门,现在要回过头恶补Ajax和json了,随手翻到dom编程艺术发现有一个适合回忆的例子,先抄录下来,引入对Ajax作用的大概印象,再去掰开了研究。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="main.css" />
</head>
<body>
<form method="POST" action="submit.html">
<fieldset>
<div>
<label for="name">用户名:</label>
<input type="text" id="name" name="name">
</div>
<div>
<label for="password">密码: </label>
<input type="password" id="password" name="password">
</div>
<button type="submit" id="send">提交</button>
<button type="reset">重置</button>
</fieldset>
</form>
<p id="holder"></p>
<script async>
function submitWithAjax(){
var form1 = document.getElementsByTagName("form")[0];//获取第一个表单元素
var request = new XMLHttpRequest();//创建一个XHR对象,就不兼容IE了哈
var dataParts = [];//创建存储数据的数组
var element;
var holder = document.getElementById("holder");
// console.log(form1.elements.length);fieldset也算一个
for(var i = 0;i<form1.elements.length;i++){
element = form1.elements[i];
dataParts[i] = element.name + '=' + encodeURIComponent(element.value);
//收集名字和其编码后的值,保存起来
}
console.log(dataParts);
var data = dataParts.join("&");//把要发送的数据用&连接起来
// console.log(data);
request.open("POST",form1.getAttribute("action"),true);//使用POST请求
request.setRequestHeader('Content-type',"application/x-www-form-urlencoded");//必需,表明请求中包含URL编码的表单
request.onreadystatechanged = function(){
if(request.readyState == 4){
if(request.status == 200 || request.status == 0){
var matches = request.responseText.match(/<p>([\s\S]+)<\/p>/);
//match方法以正则表达式为参数,返回包含各种匹配结果的数组
//match[0]是responseText中与整个模式匹配的部分,即包括<p>,</p>在内的部分,
// 而[1]是其内部的部分(与捕获组中的模式匹配的部分)
if(matches.length > 0){//捕获(匹配)成功
holder.innerHTML = matches[1];
}else{
holder.innerHTML = "<p>出错了!</p>";
}
}else{
holder.innerHTML = "<p>"+request.responseText+"</p>";
}
}
};
request.send(data);
};
var send = document.getElementById("send");
window.onload= submitWithAjax;
// form1.onsubmit = function(){
// if(submitwithajax()) return false;} </script>
</body>
</html>