PHP全棧學習筆記13

PHP全棧學習筆記13

php與ajax技術javascript

web2.0的到來,ajax逐漸成爲主流,什麼是ajax,ajax的開發模式,優勢,使用技術。(ajax概述,ajax使用的技術,須要注意的 問題,在PHP應用ajax技術的應用)php

什麼是ajax,ajax的開發模式,優勢。css

ajax是由jesse james garrett建立的,是asynchronous javascript and xml,異步javascript和xml技術,ajax並非一門新的語言或技術,它是javascript,xml,css,dom等多種技術的組合,能夠實現客戶端的異步請求操做,能夠在不刷新頁面下與服務器進行通訊,從而減小了用戶的等待時間。html

ajax開發模式:
瀏覽器(客戶端) http傳輸,http請求, web服務器 數據存儲,後端處理,繼承系統,服務器端。java

客戶端(瀏覽器)JavaScript調用,ajax引擎 http請求,http傳輸, web和xml服務器,數據存儲,後端處理,繼承系統(服務端)。mysql

優勢:減輕服務器的負擔,能夠把部分由服務器負擔的工做轉移到客戶端上,無刷新更新頁面,能夠調用xml等外部數據,基於標準化的並被普遍支持的技術。web

JavaScript是一種在web頁面中添加動態腳本代碼的解釋性程序語言。ajax

xmlhttprequestsql

ie瀏覽器把xmlhttp後端

var http_request = new ActiveXObject("Msxml2.XMLHTTP");
var http_request = new ActiveXObject("Microsoft.XMLHTTP");

mozailla,safari等其餘瀏覽器

var http_request = new XMLHttpRequest();
if(window.XMLHttpRequest){
http_request = new XMLHttpRequest();
}else if(window.ActiveXObject){
 try{
 http_request = new ActiveXObject("Msxml2.XMLHTTP");
 }catch(e){
 try{
 http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
 try{
 http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
}
}

XMLHttpRequest對象的經常使用方法:

open()方法用於設置進行異步請求目標的url

open("method", "url" [,asyncFlag [,"userName" [, "password"]]])

send()方法用於向服務器發送請求

send(content)

setRequestHeader()方法

setRequestHeader()方法爲請求的http頭設置值

setRequestHeader("label","value")

label用於指定http頭,value用於指定http頭設置值

open()方法事後才能使用setRequestHeader()方法

abort()方法
abort()方法用於中止當前異步請求

getAllResponseHeaders()方法
getAllResponseHeaders()方法用於以字符串形式完整的http頭信息。

xmlhttpRequest對象經常使用的屬性
onreadystatechange 每一個狀態改變時都會觸發這個事件處理器,一般會調用一個JavaScript函數。

readyState 請求的狀態:

0 爲未初始化
1 爲正在下載
2 爲已加載
3 在交互中
4 爲完成

responseText 服務器的響應,表示字符串

responseXML 服務器的響應,表示xml

status 返回服務器的http狀態碼
statusText 返回http狀態碼對應的文本

xml語言爲可擴展的標記語言,提供了用於描述結構化數據的格式。xmlHttpRequest對象與服務器交換的數據,一般採用xml格式。

dom爲文檔對象模型,爲xml文檔的解析定義了一組接口。

在PHP中應用AJAX技術檢測用戶名

<script language="javascript">
var http_request = false;
function createRequest(url) {
    //初始化對象併發出XMLHttpRequest請求
    http_request = false;
    if (window.XMLHttpRequest) {                                        //Mozilla等其餘瀏覽器
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            http_request.overrideMimeType("text/xml");
        }
    } else if (window.ActiveXObject) {                              //IE瀏覽器
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
           } catch (e) {}
        }
    }
    if (!http_request) {
        alert("不能建立XMLHTTP實例!");
        return false;
    }
    http_request.onreadystatechange = alertContents;                     //指定響應方法
    
    http_request.open("GET", url, true);                                 //發出HTTP請求
    http_request.send(null);
}
function alertContents() {                                               //處理服務器返回的信息
    if (http_request.readyState == 4) {
        if (http_request.status == 200) {
            alert(http_request.responseText);
        } else {
            alert('您請求的頁面發現錯誤');
        }
    }
}
</script>
<script language="javascript">
function checkName() {
    var username = form1.username.value;
    if(username=="") {
        window.alert("請填寫用戶名!");
        form1.username.focus();
        return false;
    }
    else {
        createRequest('checkname.php?username='+username+'&nocache='+new Date().getTime());
    }
}
</script>
<?php
    header('Content-type: text/html;charset=GB2312');       //指定發送數據的編碼格式爲GB2312
    $link=mysql_connect("localhost","root","root");
    mysql_select_db("db_database",$link);
    $GB2312string=iconv( 'UTF-8', 'gb2312//IGNORE' , $RequestAjaxString);           //Ajax中先用encodeURIComponent對要提交的中文進行編碼
    mysql_query("set names gb2312");
    $username=$_GET[username];
    $sql=mysql_query("select * from tb_user where name='".$username."'");
    $info=mysql_fetch_array($sql);
    if ($info){
        echo "很報歉!用戶名[".$username."]已經被註冊!";
    }else{
        echo "祝賀您!用戶名[".$username."]沒有被註冊!";
    }
?>

類別添加

<script language="javascript">
var http_request = false;
function createRequest(url) {
    //初始化對象併發出XMLHttpRequest請求
    http_request = false;
    if (window.XMLHttpRequest) {                                        //Mozilla等其餘瀏覽器
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            http_request.overrideMimeType("text/xml");
        }
    } else if (window.ActiveXObject) {                              //IE瀏覽器
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
           } catch (e) {}
        }
    }
    if (!http_request) {
        alert("不能建立XMLHTTP實例!");
        return false;
    }
    http_request.onreadystatechange = alertContents;                     //指定響應方法
    
    http_request.open("GET", url, true);                                 //發出HTTP請求
    http_request.send(null);
}
function alertContents() {                                               //處理服務器返回的信息
    if (http_request.readyState == 4) {
        if (http_request.status == 200) {
            sort_id.innerHTML=http_request.responseText;                //設置sort_id HTML文本替換的元素內容
        } else {
            alert('您請求的頁面發現錯誤');
        }
    }
}
</script>
<script language="javascript">
function checksort() {
    var txt_sort = form1.txt_sort.value;
    if(txt_sort=="") {
        window.alert("請填寫文章類別!");
        form1.txt_sort.focus();
        return false;
    }
    else {
        createRequest('checksort.php?txt_sort='+txt_sort);
    }
}
</script>
<?php
    $link=mysql_connect("localhost","root","root");
    mysql_select_db("db_database",$link);
    $GB2312string=iconv( 'UTF-8', 'gb2312//IGNORE',$RequestAjaxString);         //Ajax中先用encodeURIComponent對要提交的中文進行編碼
    mysql_query("set names gb2312");
    $sort=$_GET[txt_sort];
    mysql_query("insert into tb_sort(sort) values('$sort')");
    header('Content-type: text/html;charset=GB2312');       //指定發送數據的編碼格式爲GB2312
?>
<table border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td>
    <select name="select" >
    <?php
        $link=mysql_connect("localhost","root","root");
        mysql_select_db("db_database23",$link);
        $GB2312string=iconv( 'UTF-8', 'gb2312//IGNORE' , $RequestAjaxString);           //Ajax中先用encodeURIComponent對要提交的中文進行編碼
        mysql_query("set names gb2312");
        $sql=mysql_query("select distinct * from tb_sort group by sort");
        $result=mysql_fetch_object($sql);
        do{
            header('Content-type: text/html;charset=GB2312');       //指定發送數據的編碼格式爲GB2312
    ?>
    <option value="<?php echo $result->sort;?>" selected><?php echo $result->sort;?></option>
    <?php
        }while($result=mysql_fetch_object($sql));
    ?>
    </select>

xml基礎技術

瞭解xml,使用simpleXML解析文檔的方法
遍歷xml文檔,修改,保存xml,建立xml文檔的方法

xml語法
xml文檔結構,xml聲明,處理指令,註解,xml元素,xml屬性,使用cdata標記,xml命令空間。

XML文檔結構

<?xml version="1.0" encoding="gb2312" standalone="yes"?>
<?xml-stylesheet type="text/css" href="111.css"?>

XML聲明

<?xml version="1.0" encoding="gb2312" standalone="yes"?>

image.png

處理指令

<?xml-stylesheet type = "text/css" href="111.css"?>
<?處理指令名 處理執行信息?>

xml-stylesheet:樣式表單處理指令
type="text/css":設定了文檔所使用的樣式是css
href="111.css":設定了樣式文件的地址

image.png

XML屬性

<標籤 屬性名="屬性值" 屬性名=""…>內容</標籤>

image.png

SimpleXML
建立SimpleXML對象
Simplexml_load_file()函數,將指定的文件解析到內存中
Simplexml_load_string()函數,將建立的字符串解析到內存當中
Simplexml_load_date()函數,將一個使用dom函數建立的domDocument對象導入到內存當中

遍歷全部子元素
children()方法和foreach循環語句能夠遍歷全部子節點元素

遍歷全部屬性
SimpleXML對象中的attributes()方法

<?xml version="1.0" encoding="GB2312"?>
<exam>

</exam>
<?php
header('Content-Type:text/html;charset=utf-8');
?>

<?php
/*  第一種方法  */
$xml_1 = simplexml_load_file("5.xml");
print_r($xml_1);
/*  第二種方法  */
$str = <<<XML
<?xml version='1.0' encoding='gb2312'?>
<Object>
    <ComputerBook>
        <title>PHP</title>
    </ComputerBook>
</Object>
XML;
$xml_2 = simplexml_load_string($str);
echo '<br>';
print_r($xml_2);
/*  第三種方法  */
$dom = new domDocument();
$dom -> loadXML($str);
$xml_3 = simplexml_import_dom($dom);
echo '<br>';
print_r($xml_3);
?>
<?php
header('Content-Type:text/html;charset=utf-8');
?>
<style type="text/css">

<?php
$str = <<<XML
<?xml version='1.0' encoding='gb2312'?>
<object>
    <book>
        <computerbook>PHP</computerbook>
    </book>
    <book>
        <computerbook>PHP</computerbook>
    </book>
</object>
XML;
$xml = simplexml_load_string($str);
foreach($xml->children() as $layer_one){
    print_r($layer_one);
    echo '<br>';
    foreach($layer_one->children() as $layer_two){
        print_r($layer_two);
        echo '<br>';
    }
}
?>
<?php
$str = <<<XML
<?xml version='1.0' encoding='gb2312'?>
<object name='commodity'>
    <book type='computerbook'>
        <bookname name='22'/>
    </book>
    <book type='historybook'>
        <booknanme name='111'/>
    </book>
</object>
XML;
$xml = simplexml_load_string($str);
foreach($xml->children() as $layer_one){
    foreach($layer_one->attributes() as $name => $vl){
        echo $name.'::'.$vl;
    }
    echo '<br>';
    foreach($layer_one->children() as $layer_two){
        foreach($layer_two->attributes() as $nm => $vl){
            echo $nm."::".$vl;
        }
        echo '<br>';
    }
}
?>
<?php
    header('Content-Type:text/html;charset=utf-8');
?>

<?php
$str = <<<XML
<?xml version='1.0' encoding='gb2312'?>
<object name='商品'>
    <book>
        <computerbook>P123</computerbook>
    </book>
    <book>
        <computerbook name='456'/>
    </book>
</object>
XML;
$xml = simplexml_load_string($str);
echo $xml[name].'<br>';
echo $xml->book[0]->computerbook.'<br>';
echo $xml->book[1]->computerbook['name'].'<br>';
?>
<?php
header('Content-Type:text/html;charset=utf-8');
$str=<<<XML
<?xml version='1.0' encoding='gb2312'?>
<object name='商品'>
    <book>
        <computerbook type='12356'>123</computerbook>
    </book>
</object>
XML;

$xml = simplexml_load_string($str);
echo $xml[name].'<br />';
$xml->book->computerbook['type'] = iconv('gb2312','utf-8','PHP123');
$xml->book->computerbook = iconv('gb2312','utf-8','PHP456');
echo $xml->book->computerbook['type'].' => ';
echo $xml->book->computerbook;
?>
<?php
$xml = simplexml_load_file('10.xml');
$xml->book->computerbook['type'] = iconv('gb2312','utf-8','PHP1');
$xml->book->computerbook = iconv('gb2312','utf-8','PHP2');
$modi = $xml->asXML();
file_put_contents('10.xml',$modi);
$str = file_get_contents('10.xml');
echo $str;
?>
<?php
    //Message_XML類,繼承PHP5的DomDocument類
    class Message_XML extends DomDocument{
    //屬性
    private $Root;
    //方法
    //構造函數
    public function __construct() {
        parent:: __construct();
    //建立或讀取存儲留言信息的XML文檔message.xml
    if (!file_exists("message.xml")){
        $xmlstr = "<?xml version='1.0' encoding='GB2312'?><message></message>";
        $this->loadXML($xmlstr);
        $this->save("message.xml");
    }
    else
        $this->load("message.xml");
}
public function add_message($user,$address){  //添加數據
    $Root = $this->documentElement;
    //獲取留言消息
    $admin_id =date("Ynjhis");
    $Node_admin_id= $this->createElement("admin_id");
    $text= $this->createTextNode(iconv("GB2312","UTF-8",$admin_id));
    $Node_admin_id->appendChild($text);
    
    $Node_user = $this->createElement("user");
    $text  = $this->createTextNode(iconv("GB2312","UTF-8",$user));
    $Node_user->appendChild($text);
    
    $Node_address = $this->createElement("address");
    $text= $this->createTextNode(iconv("GB2312","UTF-8",$address));
    $Node_address->appendChild($text);

    $Node_Record = $this->createElement("record");
    $Node_Record->appendChild($Node_admin_id);
    $Node_Record->appendChild($Node_user);
    $Node_Record->appendChild($Node_address);
    //加入到根結點下
    $Root->appendChild($Node_Record);
    $this->save("message.xml");  
    echo "<script>alert('添加成功');location.href='".$_SERVER['PHP_SELF']."'</script>";
}
public function delete_message($admin_id){  //刪除數據
    $Root = $this->documentElement;
    $xpath = new DOMXPath($this);
    $Node_Record= $xpath->query("//record[admin_id='$admin_id']");
    $Root->removeChild($Node_Record->item(0));
    $this->save("message.xml");
    echo "<script>alert('刪除成功');location.href='".$_SERVER['PHP_SELF']."'</script>";
}

public function show_message(){  //讀取數據
    $root=$this-documentElement;
    $xpath=new DOMXPath($this);
    
    $Node_Record=$this->getElementsByTagName("record");
    $Node_Record_length=$Node_Record->length;
    print"<table width='506' bgcolor='#FFFFCC'><tr>";
    print"<td width='106' height='22' align='center'>";
    print"<b>用戶名</b>";
    print"</td><td width='400' align='center'>";
    print"<b>留言信息</b></td></tr>";

    for($i=0;$i<$Node_Record->length;$i++){
        $k=0;
        foreach($Node_Record->item($i)->childNodes as $articles){
           $field[$k]=iconv("UTF-8","GB2312",$articles->textContent);
            $k++;
    }
    print"<table width='506' bgcolor='#FFFFCC'><tr>";
    print"<td width='100' height='22' align='center'>";
    print"$field[1]";
    print"</td><td width='300' align='left'>";
    print"$field[2]";
    print"</td><td width='100' align='center'>";
    print"<a href='?Action=delete_message&admin_id=$field[0]'>刪除</a></td>";
    print"</tr></table>"; 
    }}
    public function post_message(){
        print "<table width='506' bgcolor='#FFFFCC'><form method='post' action='?Action=add_message'>";
        print "<tr><td  width='106'height='22'>&nbsp;&nbsp;&nbsp;&nbsp;用戶名:</td><td><input type=text name='user' size=50></td></tr>";
        print "<tr><td width='106' height='22'>&nbsp;&nbsp;&nbsp;&nbsp;留言信息:</td><td width='400'><textarea name='address' cols='48' rows='5' id='address'></textarea></td></tr>";
        print "<tr><td width='106' height='30'>&nbsp;&nbsp;<input type='submit' value='添加數據'></td><td align='right'><a href=?Action=show_message>查看數據</a>&nbsp;&nbsp;&nbsp;&nbsp;</td></tr></form></table>";
    }

}
?>

<html>                                                                                                                           
    <head>                                                                                                                  
    <title>定義一個PHP讀取XML類</title>                                                                                        
        <style>
        td,body{font-size:12px}
        a:link {
    text-decoration: none;
}
a:visited {
    text-decoration: none;
}
a:hover {
    text-decoration: none;
}
a:active {
    text-decoration: none;
}
</style>                                                                                      
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312"></head>                                                                                                                        
<body>                                                                                                                         
<table width=506 height=50 border=0 cellpadding=0 cellspacing=0 bgcolor="#33BE6B">                                
                                                                                                                          
        <tr>                                                                                                                         
          <td width="506" height=50 valign="bottom" background="title.gif"><table width="506">
            <tr>
              <td height="24" align="right" scope="col">&nbsp;&nbsp;<a href=?Action=post_message>添加數據</a>&nbsp;&nbsp;&nbsp;</td>
            </tr>
          </table></td>
        </tr>  
        <?php                                                                                       
        $HawkXML = new Message_XML;     
        $Action ="";      
        if(isset($_GET['Action']))     
              $Action = $_GET['Action'];                                                                                       
        switch($Action){                                                                                            
            case "show_message":        //查看                                                                               
                $HawkXML->show_message();                                                                         
                break;                                                                                                     
            case "post_message":        //提交                                                                               
                $HawkXML->post_message();                                                                       
                break;                                                                                                      
            case "add_message":          //添加                                                                            
                $HawkXML->add_message($_POST['user'],$_POST['address']);                                             
                break;    
            case "delete_message":      //刪除
                $HawkXML->delete_message($_GET['admin_id']);
                break;
        }                                                                                                
       ?>   
</table>                                                                                                                   
</body>                                                                                                                      
</html>
<?php
    //Message_XML類,繼承PHP5的DomDocument類
    class Message_XML extends DomDocument{
    //屬性
    private $Root;
    //方法
    //構造函數
    public function __construct() {
        parent:: __construct();
    //建立或讀取存儲留言信息的XML文檔message.xml
    if (!file_exists("message.xml")){
        $xmlstr = "<?xml version='1.0' encoding='GB2312'?><message></message>";
        $this->loadXML($xmlstr);
        $this->save("message.xml");
    }
    else
        $this->load("message.xml");
}
public function add_message($user,$address){  //添加數據
    $Root = $this->documentElement;
    //獲取留言消息
    $admin_id =date("Ynjhis");
    $Node_admin_id= $this->createElement("admin_id");
    $text= $this->createTextNode(iconv("GB2312","UTF-8",$admin_id));
    $Node_admin_id->appendChild($text);
    
    $Node_user = $this->createElement("user");
    $text  = $this->createTextNode(iconv("GB2312","UTF-8",$user));
    $Node_user->appendChild($text);
    
    $Node_address = $this->createElement("address");
    $text= $this->createTextNode(iconv("GB2312","UTF-8",$address));
    $Node_address->appendChild($text);

    $Node_Record = $this->createElement("record");
    $Node_Record->appendChild($Node_admin_id);
    $Node_Record->appendChild($Node_user);
    $Node_Record->appendChild($Node_address);
    //加入到根結點下
    $Root->appendChild($Node_Record);
    $this->save("message.xml");  
    echo "<script>alert('添加成功');location.href='".$_SERVER['PHP_SELF']."'</script>";
}

public function show_message(){  //讀取數據
    $root=$this-documentElement;
    $xpath=new DOMXPath($this);
    
    $Node_Record=$this->getElementsByTagName("record");
    $Node_Record_length=$Node_Record->length;
    print"<table width='506' bgcolor='#FFFFCC'><tr>";
    print"<td width='106' height='22' align='center'>";
    print"<b>用戶名</b>";
    print"</td><td width='400' align='center'>";
    print"<b>留言信息</b></td></tr>";

    for($i=0;$i<$Node_Record->length;$i++){
        $k=0;
        foreach($Node_Record->item($i)->childNodes as $articles){
           $field[$k]=iconv("UTF-8","GB2312",$articles->textContent);
            $k++;
    }
    print"<table width='506' bgcolor='#FFFFCC'><tr>";
    print"<td width='100' height='22' align='center'>";
    print"$field[1]";
    print"</td><td width='400' align='left'>";
    print"$field[2]";
    print"</td>";
    print"</tr></table>"; 
    }}
    public function post_message(){
        print "<table width='506' bgcolor='#FFFFCC'><form method='post' action='?Action=add_message'>";
        print "<tr><td  width='106'height='22'>&nbsp;&nbsp;&nbsp;&nbsp;用戶名:</td><td><input type=text name='user' size=50></td></tr>";
        print "<tr><td width='106' height='22'>&nbsp;&nbsp;&nbsp;&nbsp;留言信息:</td><td width='400'><textarea name='address' cols='48' rows='5' id='address'></textarea></td></tr>";
        print "<tr><td width='106' height='30'>&nbsp;&nbsp;<input type='submit' value='添加數據'></td><td align='right'><a href=?Action=show_message>查看數據</a>&nbsp;&nbsp;&nbsp;&nbsp;</td></tr></form></table>";
    }

}
?>
<html>                                                                                                                           
    <head>
    <title>使用XML來存儲少許的數據</title>                                                                                 
    <style>
    td,body{font-size:12px}
    a:link {
    text-decoration: none;
}
a:visited {
    text-decoration: none;
}
a:hover {
    text-decoration: none;
}
a:active {
    text-decoration: none;
}
</style>                                                                                      
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312"></head>                                                                                                                        
<body>                                                                                                                         
<table width=506 height=50 border=0 cellpadding=0 cellspacing=0 bgcolor="#33BE6B">                                
                                                                                                                          
        <tr>                                                                                                                         
          <td width="506" height=50 valign="bottom" background="title.gif"><table width="506">
            <tr>
              <td height="24" align="right" scope="col">&nbsp;&nbsp;<a href=?Action=post_message>添加數據</a>&nbsp;&nbsp;&nbsp;</td>
            </tr>
          </table></td>
        </tr>  
        <?php                                                                                       
        $HawkXML = new Message_XML;     
        $Action ="";      
        if(isset($_GET['Action']))     
              $Action = $_GET['Action'];                                                                                       
        switch($Action){                                                                                            
            case "show_message":        //查看                                                                               
                $HawkXML->show_message();                                                                         
                break;                                                                                                     
            case "post_message":        //提交                                                                               
                $HawkXML->post_message();                                                                       
                break;                                                                                                      
            case "add_message":          //添加                                                                            
                $HawkXML->add_message($_POST['user'],$_POST['address']);                                             
                break;    }                                                                                                
         ?>
</table>                                                                                                                   
</body>                                                                                                                      
</html>

結言

好了,歡迎在留言區留言,與你們分享你的經驗和心得。

感謝你學習今天的內容,若是你以爲這篇文章對你有幫助的話,也歡迎把它分享給更多的朋友,感謝。

感謝!承蒙關照!您真誠的讚揚是我前進的最大動力!

image

image

相關文章
相關標籤/搜索