JAVASCRIPT - AJAX基礎知識

//創建XMLHttpRequest對象
var xhr;
if (window.XMLHttpRequest) {
    // code for IE7+、Firefor、Chrome、Opera、Safari
    xhr = new XMLHttpRequest();
} else {
    // code for IE6、IE5
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
}


//向服務器發送GET請求, GET在發送請求是有時候是會有緩存的,所以需要加上隨機數,true 代表的是異步交互, send 發送
xhr.open("GET", "www.baidu.com?t=" + Math.random(), true);
//發送請求
xhr.send();




//向服務器發送POST請求,
xhr.open("POST", "www.baidu.com", true);
//在發送之前需要設置頭信息(HTTP協議),通過set設置頭信息(setRequestHeader),參數二爲設置編碼格式爲
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//發送請求,send()方法中規定您希望發送的數據
xhr.send("fname=Bill&lname=Gates");
/*
    發送時選擇GET還是POST ?
        1、與POST相比,GET更簡單也更快,並且在大部分情況下都能使用
    什麼情況下使用POST請求
        1、無法使用緩存文件(更新服務器的文件或數據庫) add
        2、向服務器發送大量數據(POST沒有數據量限制)
        3、發送包含未知字符的用戶輸入時,POST比GET更穩當也更靠譜
    XMLHttpRequest對象的三個重要的屬性:
        1、readyState屬性:存有XMLHttpRequest的狀態信息,從0到4發生的變化。
            0:請求爲初始化
            1:服務器連接已建立
            2:請求已接受
            3:請求處理中
            4:請求已完成,且響應已就緒
        2、onreadystatechange屬性:每當readyState改變時,就會觸發onreadystatechange事件
        3、Status狀態屬性: 
            200:" ok "
            404:未找到頁面
*/
//完成請求成功代碼
xhr.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
        //執行成功,this.responseText 或者 this.responseXML
        //onreadystatechange事件被觸發5次(0-4),對應着readyState的每個變化
    }
}




/*
PHP請求簡單完整請求代碼:
    <!--
$xxx:    什麼變量
$name: 獲取XMLHTTP請求參數
$dsn: 數據庫信息
$db: 連接數據庫  參數1、數據庫地址及數據庫名稱  參數2、數據用戶名   參數3、數據庫密碼
$_res: query ”執行sql語句“ 增刪改查
fetch():fetch函數表示查詢到了
-->
<?php
$name =$_POST['username']; 
$dsn = "mysql:host=localhost;dbname=zhangsan";
$db = new PDO($dsn,'root','');
$_res =$db->query("select * from 表名  where 列名='" $name "'");
if($res ->fetch()){
echo 0;
}else{
echo 1;
}



 Javascript XMLHttpRequest請求簡單代碼
    var name = "張三";
    var xhr;
    if(windw.XMLHttpRequest){
        xhr  = new XMLHttpRequest();
    }else{
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    //GET請求方式一
    // xhr.open("get","www.baidu.com?t="+Math.random(),ture);
    // xhr.send();
    //POST請求方式一
    xhr.open("post","www.baidu.com",ture);
    xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xhr.send("username="+name);
    xhr.onreadystatechange = function(){
        if(this.readyState ==4 && this.Status ==200){
            //請求成功後接受返回數據
            if(this.responseText !=1){
                alert("不可以註冊")
            }else{
                alert("可以註冊");
            }
        }
    }

*/

發佈了36 篇原創文章 · 獲贊 12 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章