ajax

这是js原生的ajax:

html:

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8" />
 5         <title></title>
 6     </head>
 7     <body>
 8         <button onclick="ajaxDemo()">ajax</button>
 9     </body>
10 </html>
11 <!--js原生的ajax-->
12 <script>
13     function ajaxDemo(){
14         //创建ajax对象
15         var xhr = new XMLHttpRequest();
16         //监听ajax的状态 到哪一步
17         xhr.onreadystatechange = function(){
18             if(xhr.readyState == 4){
19                 //数据处理
20                 alert(xhr.responseText);
21             }
22         }
23         //发送请求 get写null post写键值对
24         //xhr.open('GET','index.php?id=1');
25         xhr.open('POST','index.php');
26         //post传值这个东西必须写    post请求必须设置他的头信息
27         xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
28         var data = "id=1&type=add";
29         xhr.send(data);
30         
31         
32         
33         //xhr.send(null);
34     }
35     
36     
37 </script>

php:

<?php
echo $_GET['id'];
?>

只用看看就可以,一般用juquery写ajax:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script type="text/javascript" src="jquery-3.2.1.min.js"></script>
    </head>
    <body>
    </body>
</html>
<script>
    $.ajax({
        type:"post", //请求方式  不写默认get
        url:"index.php",
        //async:true, 同步异步  默认是异步true
        data:{id:1,name:"lisi"}, //数据
        dataType:'text', //返回数据类型 不写默认text json xml
        success:function (data) {
            
        }
    });
</script>

ajax的两大优点是不用刷新页面,可以异步。

ajax可以将数据传送到后台并接收返回的数据,form表单只能将数据发送到后台而无法接收数据。

posted @ 2019-01-06 13:29  梁栋  阅读(103)  评论(0编辑  收藏  举报