关于Ajax

1.干什么的?

ajax负责抓取用户名信息,传递给服务器进行校验;

2.属性:
  onreadystatechange:事件,该事件可以感知ajax状态(readyState)的变化。ajax请求过程中要随时感知其状态  

  readyState:表示ajax状态值

     ajax有5种状态readyState:
          0------> 创建ajax对象完毕
          1------> 有调用open()方法
          2------> 有调用send()方法
          3------> 服务器端数据只返回了一部分
          4------> 服务器端数据全部返回,ajax请求完成

  responseText:以字符串形式接收服务器端返回的信息

3.方法:
       open():创建一个新的http请求

       send():发送请求到服务器

  例如:

    get:$xhr.open("get","123.php?a=1&b=2");$xhr.send(null);  //如果方式为get,则send为null

    post:$xhr.open("post","123.php);post方法的对应的send:

    //(要在open()方法执行之后设置)

    xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');

    var info = "name=abc&age=20";

    xhr.send(info);

 4.同步异步:

async:true/false,

true(默认):异步。同时可进行多个操作。

false:同步。同一时间只能进行一个操作。

5.页面跳转

ajax不能从php页面直接进行跳转,只是返回一个数据。要想跳转页面要从js跳转。

 1 <!doctype html>
 2 <html>
 3 <head>
 4 <meta charset="utf-8">
 5 <title>三级联动</title>
 6 </head>
 7 
 8 <body>
 9 省:<select name="" id="sheng" onChange="selshi(this)">
10         <option value="">请选择</option>
11 </select>
12 市:<select name="" id="shi" onChange="selqu(this)">
13         <option value="">请选择</option>
14 </select>
15 区:<select name="" id="qu">
16         <option value="">请选择</option>
17 </select>
18 </body>
19 </html>
20 <script>
21     var attr = [];
22     //页面加载完成显示省的内容
23     window.onload = function(){
24         //发起请求
25         sendInfo("sheng");
26     }
27     function sendInfo(type,code=0){
28         //创建对象
29         var xhr = new XMLHttpRequest();
30         //监听ajax状态
31         //responseText(返回值)
32         xhr.onreadystatechange = function(){
33             if(xhr.readyState == 4){
34                 //处理数据
35                 chuliData(xhr.responseText,type);
36                 
37             }
38         }
39         //创建请求
40         xhr.open("get","conn_db.php?type="+type+"&code="+code);
41         //发送请求
42         xhr.send(null);
43     }
44     function chuliData(data,type){
45         //将字符串转为二维字符数组arr:1,山东;3,河北;
46         var arr = data.split(";");
47         var str = '';
48         for(var i = 0; i < arr.length; i++){
49             //拆分二维数组为:1,山东
50             attr[i] = arr[i].split(",");
51             //option的value = 1,内容 = 山东
52             str += '<option value="'+attr[i][0]+'">'+attr[i][1]+'</option>';
53         }
54         console.log(str);
55         document.getElementById(type).innerHTML = str;
56     }
57     function selshi(obj){
58         sendInfo('shi',obj.value);
59     }
60     function selqu(obj){
61         sendInfo('qu',obj.value);
62     }
63 </script>
三级联动示例:html+js部分

相关文章:

  • 2022-01-11
  • 2022-02-21
  • 2021-12-09
  • 2021-12-05
  • 2022-01-19
  • 2022-01-18
  • 2022-12-23
猜你喜欢
  • 2022-02-24
  • 2021-07-13
  • 2022-02-18
  • 2022-01-03
  • 2022-01-03
  • 2021-12-08
  • 2021-12-26
相关资源
相似解决方案