Ajax提交post請求案例分析

這篇文章主要介紹了Ajax提交post請求,結合具體案例形式分析了ajax提交post請求相關原理、用法及操作注意事項,需要的朋友可以參考下

本文實例講述了Ajax提交post請求。分享給大家供大家參考,具體如下:

前言:博主之前有篇文章是快速入門Ajax ,主要是利用Ajax做簡單的get請求,今天給大家分享一篇利用Ajax提交post請求,以及使用post時需要注意的地方,還是以案例的方式告訴大家。

案例:

註冊表單

文件結構圖:

這裏寫圖片描述

06-ajax-reg.html文件:

頁面中主要有一個表單,使用了onsubmit事件,在onsubmit事件中首先獲取準備post的內容,然後創建XMLHttpRequest對象,接着確定請求參數,然後重寫回調函數,在函數中主要是根據請求的狀態來使用服務器端返回值,然後發送請求,最後返回false,讓表單無法提交,從而頁面也不會跳轉。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>無刷新用戶註冊界面</title>
  <link rel="stylesheet" href="">
</head>
<script>
  //創建XMLHttpRequest對象
  function createXhr(){
    var xhr = null;
    if(window.XMLHttpRequest){
      xhr = new XMLHttpRequest();//谷歌、火狐等瀏覽器
    }else if(window.ActiveXObject){
      xhr = new ActiveXObject("Microsoft.XMLHTTP");//ie低版本
    }
    return xhr;
  }
  //註冊方法
  function reg(){
    //1、獲取準備Post內容
    var username = document.getElementsByName('username')[0].value;
    var email = document.getElementsByName('email')[0].value;
    //2、創建XMLHttpRequest對象
    var xhr = createXhr();
    //3、確定請求參數
    xhr.open('POST','./06-ajax-reg.php',true);
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    //4、重寫回調函數
    xhr.onreadystatechange = function(){
      if(this.readyState == 4 && this.status == 200){
        //使用服務器端返回值
        var regres = document.getElementById('regres');
        regres.innerHTML = this.responseText;
      }
    }
    //5、發送請求
    var content = 'username='+username+'&email='+email;
    xhr.send(content);
    return false;//不跳轉頁面
  }
</script>
<body>
  <h1>無刷新用戶註冊界面</h1>
  <form onsubmit="return reg();">
    用戶名:<input type="text" name="username" /><br/>
    郵箱:<input type="text" name="email" /><br/>
    <input type="submit" value="註冊" />
  </form>
  <div id="regres"></div>
</body>
</html>

06-ajax-reg.php文件:

代碼比較簡單,主要是判斷內容是否爲空,爲空則返回“內容填寫不完整”,不爲空則打印提交的內容,返回“註冊成功”。

<?php
/**
 * ajax註冊程序
 * @author webbc
 */
header('Content-type:text/html;charset=utf-8');
if(trim($_POST['username']) == '' || trim($_POST['email']) == ''){
  echo '內容填寫不完整';
}else{
  print_r($_POST);
  echo '註冊成功';
}
?>

效果圖:

這裏寫圖片描述

注意事項:

博主以前使用過Jquery的Ajax,使用$.post函數時不需要指定請求頭的Content-Type內容爲application/x-www-form-urlencoded,是因爲jquery裏面內置了,但是使用原生的Ajax,也就是XMLHttpRequest函數時必須加上。

XMLHttpRequest發送post請求時必須設置以下請求頭:

xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

更多關於ajax相關內容感興趣的讀者可查看本站專題:《jquery中Ajax用法總結》、《JavaScript中ajax操作技巧總結》、《PHP+ajax技巧與應用小結》及《asp.net ajax技巧總結專題

希望本文所述對大家ajax程序設計有所幫助。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章