PHPとAjax技術

アヤックス主流になっWeb2.0のの到着は、AJAX、AJAX開発モデル、技術の使用の利点は何です。(概要アヤックス、AJAX技術を使用し、PHPアプリケーションのAJAX技術の応用、問題に注意が必要です)

アヤックス、AJAX開発モデル、利点は何ですか。

アヤックスは、ジェシー・ジェームス・ギャレットによって作成された非同期JavaScriptとXML、Ajaxは新しい言語や技術ではないJavaScriptとXML技術、非同期であり、それは技術のjavascriptの組み合わせで、XML、CSS、DOMなど、達成することができています非同期クライアントの要求操作することにより、ユーザのための待ち時間を減らすこと、ページを更新せずにサーバーと通信することができます。

Ajaxの開発モデル:
ブラウザ(クライアント)伝送HTTP、HTTPリクエスト、Webサーバのデータストレージ、バックエンド処理、レガシーシステム、サーバ側。

呼び出すJavaScriptのクライアント(ブラウザ)、AJAXエンジンhttpリクエストは、http送信、WebおよびXMLサーバ、データストレージ、バックエンド処理、継承システム(サーバー)。

メリット:サーバーの負担を軽減するために、あなたはページを更新せずに、クライアントにサーバー上の作業負担で更新を転送の一部を置くことができ、あなたは、標準化され、かつ広くサポートに基づいて外部データxmlおよびその他の技術を呼び出すことができます。

JavaScriptは、Webページに動的なスクリプトコードを追加すると解釈プログラミング言語です。

XMLHttpRequestの

ブラウザの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オブジェクトの一般的な方法:

ターゲットの非同期要求を設定するためのURL open()メソッド

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

サーバーにリクエストを送信するため()メソッドを送信

send(content)

setRequestHeader()メソッド

setRequestHeader HTTPヘッダの設定値()メソッド要求

setRequestHeader("label","value")

HTTPヘッダはHTTPヘッダを指定した設定値のラベル、値を指定します

open()方法过后才能使用setRequestHeader()方法

アボート()メソッド
アボート()メソッドは、現在の非同期要求を停止するために使用されています

getAllResponseHeaders()メソッド
getAllResponseHeaders()メソッドは、文字列のHTTPヘッダ情報を完了するために使用されます。

XMLHttpRequestオブジェクトは、一般的に使用される属性は、
それぞれの状態変化が、このイベントハンドラ、通常はJavaScriptの関数呼び出しをトリガーしますonreadystatechangeに。

リクエストのreadyStateのステータス:

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

代表ResponseTextサーバーの応答文字列

responseXMLサーバの応答は、XMLを示し、

HTTPサーバのステータスは、ステータスコードが返された
テキストのhttpを対応するステータスコードを返すSTATUSTEXT

XML拡張可能マークアップ言語は、構造化データを記述するためのフォーマットを提供する言語です。データは通常、xml形式で、XMLHttpRequestを、サーバと交換オブジェクト。

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の基礎となる技術

するためのSimpleXMLの方法を使用して文書を解析し、XMLを学ぶ
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-スタイルシート:スタイルシート処理命令
タイプ=「テキスト/ CSS」:使用する文書のスタイルを設定するCSSはある
のhref =「111.css」:アドレススタイルファイルを設定します

image.png

XML属性

<标签 属性名="属性值" 属性名=""…>内容</标签>

image.png

SimpleXMLを
作成するのSimpleXMLオブジェクト
simplexml_load_file()関数を、メモリに解析し、指定したファイル
()関数は、メモリに分割の列作成simplexml_load_string
Simplexml_load_date()関数は、メモリは、その中にDOMDOCUMENT関数を使用してオブジェクトは、DOMを作成します

すべての子要素の横断
子供は()メソッドと、foreachループは、要素のすべての子をトラバースすることができます

すべてのプロパティ横断
のSimpleXMLオブジェクト属性()メソッド

<?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> 

 

おすすめ

転載: www.cnblogs.com/daofaziran/p/11571889.html