1.获取表单
2.获取下拉选项
3.提交表单
4.Ajax
Ajax
异步无刷新技术
原生Ajax的实现流程
1.得到XMLHttpRequest对象
ar xhr = new XMLHttpRequest();
2.打开请求
xhr. open(method , uri, async);
method:请求方式,通常是GET |POST
uri:请求地址
async:是否异步。如果是true表示异步,false表示同步
3.发送请求
xhr. send(params);
params:请求时需要传递的参数
如果是GET请求,设置null。(GEt请求的参数设置在url后面)
如果是POST请求,无参数设置为null,有参数则设置参数
4.接收响应
xhr.status响应状态(200=响应成功,404=资源未找到,500=服务器异常)
<script type="text/javascript">
/*同步请求*/
function test01(){
// 得到XMLHttpRequest对象
var xhr = new XMLHttpRequest();
console.log(xhr.readyState);
//打开请求
xhr.open("get","data.json",false);//同步请求
console.log(xhr.readyState);
//发送请求
xhr.send(null);
console.log(xhr.readyState);
//判断响应状态
if(xhr.status == 200) {
console.log(xhr.responseText);
}
else{
console.log("状态码: " + xhr.status + ",原因: " + xhr.responseText);
}
console.log("同步请求...");
}
//同步请求
// test01();
<script type="text/javascript">
/*异步请求*/
function test02(){
// 得到XMLHttpRequest对象
var xhr = new XMLHttpRequest();
//打开请求
xhr.open("get","data.json",true);//异步请求
//发送请求
xhr.send(null);
/*
由于是异步请求,所以需要知道后台已经将请求处理完毕,才能获取响应结果
通过监听readyState的变化来得知后面的处理状态 4 = 完全处理
xhr.onreadyStatechange = function(){
}
*/
xhr.onreadystatechange = function(){
//当readyState的值为4时,表示结果成功响应
if(xhr.readyState == 4) {
//判断响应状态
if(xhr.status == 200) {
console.log(xhr.responseText);
}
else{
console.log("状态码: " + xhr.status + ",原因: " + xhr.responseText);
}
}
}
console.log("异步请求...");
}
//异步请求
test02();