码迷,mamicode.com
首页 > Web开发 > 详细

Ajax --- 数据请求

时间:2017-01-01 23:48:38      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:get   回调函数   orm   pre   send   登录   admin   www   ros   

下面主要介绍(JS原生)数据请求的主要步骤:

Ajax 数据请求步骤:

1、创建XMLHttpRequest对象
2、准备数据发送
3、执行发送
4、指定回掉函数

 

第一步:创建XMLHttpRequest对象

1 var xhr = new XMLHttpRequest();                            //  标准浏览器
2                     
3 var xhr = new ActiveXObject(‘Microsoft.XMLHTTP‘);          //  IE6

 

第二步:使用 open() 方法将参数传入

1 xhr.open(‘get‘,‘./check.php?username=‘+uname+‘&password=‘+pw,true);   // get 请求方式
2 
3 xhr.open(‘post‘,‘./01check.php‘,true);                                // post 请求方式

 

第三步:使用 send() 方法将请求发送值服务器

1 xhr.send(null);       // get 请求方式时,此处值为 null2 
3 xhr.send(请求地址);   // post 请求方式时,此处值为 请求地址

 

第四步:执行回掉函数

1 xhr.onreadystatechange = function(){            
2   if(xhr.readyState == 4){        // 4表示服务器返回的数据已经可以使用了,但是这个数据不一定是正常的
3     if(xhr.status == 200){      // 这里的200表示数据是正常的
4        alert(xhr.responseText);
5     }
6   }
7 }
8 </script>

 

综合:

 1 ==================================== html 页面  ============================================
 2     <form>
 3   用户名:
 4         <input type="text" name="username" id="username"><span id="info"></span>
 5         <br> 密码:
 6         <input type="text" name="password" id="password">
 7         <input type="button" value="登录" id="btn">
 8     </form>
 9 
10 <script>
11 var uname = document.getElementById(‘username‘).value;
12 var pw = document.getElementById(‘password‘).value;
13 
14 // 1、创建XMLHttpRequest对象
15 var xhr = null;
16 if(window.XMLHttpRequest){
17      xhr = new XMLHttpRequest();//标准
18 }else{
19      xhr = new ActiveXObject("Microsoft");//IE6
20 }
21 
22 // 2、准备发送
23 xhr.open(‘post‘,‘post.php‘,true);
24 
25 // 3、执行发送动作
26 xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");   // 如 get 此步骤省略
27 xhr.send(‘username=‘+uname+‘&password=‘+pw);               //post请求参数在这里传递,并且不需要转码
28 
29 // 4、指定回调函数
30 xhr.onreadystatechange = function(){            
31 if(xhr.readyState == 4 && xhr.status == 200){        // 4表示服务器返回的数据已经可以使用了,这里的200表示数据是正常的
32      var data = xhr.responseText;
33      if(data == ‘1‘){
34           info.innerHTML == ‘登录成功‘;
35      }
36      else if(data == ‘2‘){
37           info.innerHTML == ‘用户名或密码错误‘;
38      }else{
39           info.innerHTML == ‘服务器错误‘;
40      }
41 }
42 }
43 </script>
44 
45 =========================================== post.php 页面 ========================================
46 <?php
47     $uname = $_POST[‘username‘];
48     $pw = $_POST[‘password‘];
49 
50     if($uname == ‘admin‘ && $pw == ‘123‘){
51         echo 1;
52     }else{
53         echo $uname;
54     }
55  ?>

 注:以上是个人对原型链的理解及总结,如有笔误的地方还请大家多指教!

Ajax --- 数据请求

标签:get   回调函数   orm   pre   send   登录   admin   www   ros   

原文地址:http://www.cnblogs.com/1216zero/p/6241697.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!