ajax 原生 post

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Document</title>
 6 </head>
 7 <body>
 8 <h1>ajax 发送post</h1>
 9     <input type="text"  value="" placeholder="请输入你爱吃的菜" id='foodText'>
10     <input type="button"  value="ajaxPost请求" id='btnAjax'>
11 </body>
12 </html>
13 <script type="text/javascript">
14     document.querySelector("#btnAjax").onclick = function () {
15         var ajax = new XMLHttpRequest();
16 
17         // 使用post请求
18         ajax.open('post','ajax_post.php');
19 
20         // 如果 使用post发送数据 必须 设置 如下内容
21         // 修改了 发送给 服务器的 请求报文的 内容
22         // 如果需要像 HTML 表单那样 POST 数据,请使用 setRequestHeader() 来添加 HTTP 头。然后在 send() 方法中规定您希望发送的数据:
23         ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
24         // 发送
25         // post请求 发送的数据 写在 send方法中 
26         // 格式 name=jack&age=18 字符串的格式
27         ajax.send('name=jack&age=998');
28 
29         // 注册事件
30         ajax.onreadystatechange = function () {
31             if (ajax.readyState==4&&ajax.status==200) {
32                 console.log(ajax.responseText);
33             }
34         }
35     }
36 </script>

 

posted @ 2017-03-06 18:10  北漂阿猫  阅读(186)  评论(0编辑  收藏  举报