XMLHttpRequest and AJAX for PHP programmers, Part 2
PHP程序员需要了解的XMLHttpRequest和AJAX 第二部分
James Kassemi
翻译:rollenc
Let's Jump Right In!
我们继续!
This week's article takes off where last week's tutorial left off--we're about to jump into the creation of the PHP backend! If you haven't read the previous article, we recommend that you begin there before moving forward so you don't miss anything.
通过上周的学习,本周文章开始正式开始了。我们准备开始编辑PHP后台!如果你还没有阅读上一篇文章,我们建议你先阅读它,不要拉下必要的知识。
Calling the Functions
调用函数
Now, how is the products.html page supposed to call these functions? We want to be able to let the user select an item, and then load the values based on that selection. Using a "Search" or "Go" button is a little archaic, so let's use the onChange method, which we can use to call javascript functions whenever the user changes the selected item. Change the <select> tag in products.html to look like this:
那现在,products.html如何来调用这些函数呢 ?我们需要在用户选择条目后,加载与这个条目相关的信息。使用“搜索”或“go”显得有点老套,所以我们使用了onChange方法(事件),当用户改变选择的条目时,我们通过JAVASCRIPT来调用。将products.html文件中的<select>标签修改成这样:
<select name="select_category_select" onChange="getProducts();" />
Whenever a user changes his selection in the select box, getProducts() will be called. So, now that we've got a script that sends some data to a PHP file and receives data returned from a PHP file, we need to program the PHP file.
一旦用户改变了选择框中的选项,getProducts()就会被调用。这样我们已经编写好了发送请求和接受数据的脚本,我们接下来需要的是编写PHP文件。
Programming the PHP back-end
编写PHP后台
In our javascript function getProducts(), we made a call to the following:
在Javascript函数getProducts(),我们做了这样的调用:
http.open('get', 'internal_request.php?action=get_products&id=' + document.getElementById('product_categories').selectedIndex);
So we obviously need a PHP script that handles the action and id arguments from a GET request.
<?php
/* You should implement error checking, but for simplicity, we avoid it here */
/* 你可以进行错误处理,但为了简洁,我们略过了这些。 */
if($_GET['action'] == 'get_products'){
/* We're here to get the product listing...
You can obviously change this file to include many
different actions based on the request.
*/
switch($_GET['id']){
/* We had the following in our list.
0 Audio
1 Games
2 Internet
The integer value on the left is the value
corresponding to the javascript selectedIndex
property.*/
case 0: // Audio Programs
/* Print HTML to fill the product_cage <div>
Any output to the browser will be
retrieved in the XMLHttpRequest object's
responseText property */
echo '
<ul>
<li>CDex</li>
<li>CoolEdit</li>
<li>Winamp</li>
<li>XMMS</li>
</ul>';
break;
case 1: //Games
echo '
<ul>
<li>Blackjack</li>
<li>Calculatron</li>
<li>Hold\'em</li>
<li>Minesweeper</li>
<li>Tetris</li>
</ul>';
break;
case 2: //Internet
echo '
<ul>
<li>Epiphany</li>
<li>Internet Explorer</li>
<li>Mozilla</li>
<li>Netscape</li>
<li>Opera</li>
<li>Safari</li>
</ul>';
break;
default:
echo '<b>You didn\'t select an item from above!</b>';
break;
}
}
?>
Save the above in a file called internal_request.php.
保存以上文件为internal_request.php.
Browse to products.html using your favorite browser, and select one of the category options. You'll see the product_cage div change according to which items you selected. It may not seem like much with all the work that you put into it, but giving the user the ability to search and receive results while on the same page is great. Imagine posting to a forum without leaving the thread, or even something similar to the above for a large corporation with thousands of products. Bandwidth saved is money saved, and your company will no doubt appreciate that.
在你喜欢的浏览器中打开products.html,选择一个选项,你会发现,名称为product_cage的DIV内容根据你的选择改变了。这并不是所有的好处。想象一下,如果在论坛上恢复一篇文章而不需要重新刷新本页,或者当网站拥有成千上万的产品时,毫无疑问,贵公司会因为流量的节省而高兴的。
There are many resources available to learn more about AJAX and the XMLHttpRequest object, and now that you know the basics, you shouldn't have any problem expanding your knowledge to fit your application. Good luck!
有许多可以利用和学习的Ajax,XMLHttpRequest的知识,到现在你只是了解到了一些基础知识而已。希望你不会因为进一步学习和应用而遇到困惑。祝你好运!
Source for Included File: products.html
products.html的源代码:
<html>
<head>
<title>CompanyXYZ Software</title>
<script language="javascript" type="text/javascript"
src="./internal_request.js">
</script>
</head>
<body>
<div id="product_categories">
<!--Category selection box...-->
<form name="form_category_select">
<select name="select_category_select" onChange="getProducts();">
<option>Audio</option>
<option>Games</option>
<option>Internet</option>
</select>
</form>
</div>
<div id="product_cage">
<!--This is where we'll be displaying the products once they're loaded-->
^ Please select a category from above.
</div>
</body>
</html>
Source for Included File: internal_request.js
products.html的源代码:
/* The following function creates an XMLHttpRequest object... */
function createRequestObject(){
var request_o; //declare the variable to hold the object.
var browser = navigator.appName; //find the browser name
if(browser == "Microsoft Internet Explorer"){
/* Create the object using MSIE's method */
request_o = new ActiveXObject("Microsoft.XMLHTTP");
}else{
/* Create the object using other browser's method */
request_o = new XMLHttpRequest();
}
return request_o; //return the object
}
/* You can get more specific with version information by using
parseInt(navigator.appVersion)
Which will extract an integer value containing the version
of the browser being used.
*/
/* The variable http will hold our new XMLHttpRequest object. */
var http = createRequestObject();
/* Function called to get the product categories list */
function getProducts(){
/* Create the request. The first argument to the open function is the method (POST/GET),
and the second argument is the url...
document contains references to all items on the page
We can reference document.form_category_select.select_category_select and we will
be referencing the dropdown list. The selectedIndex property will give us the
index of the selected item.
*/
http.open('get', 'internal_request.php?action=get_products&id='
+ document.form_category_select.select_category_select.selectedIndex);
/* Define a function to call once a response has been received. This will be our
handleProductCategories function that we define below. */
http.onreadystatechange = handleProducts;
/* Send the data. We use something other than null when we are sending using the POST
method. */
http.send(null);
}
/* Function called to handle the list that was returned from the internal_request.php file.. */
function handleProducts(){
/* Make sure that the transaction has finished. The XMLHttpRequest object
has a property called readyState with several states:
0: Uninitialized
1: Loading
2: Loaded
3: Interactive
4: Finished */
if(http.readyState == 4){ //Finished loading the response
/* We have got the response from the server-side script,
let's see just what it was. using the responseText property of
the XMLHttpRequest object. */
var response = http.responseText;
/* And now we want to change the product_categories <div> content.
we do this using an ability to get/change the content of a page element
that we can find: innerHTML. */
document.getElementById('product_cage').innerHTML = response;
}
}
Source for Included File: internal_request.php
internal_request.php的源代码:
<?php
/* You should implement error checking, but for simplicity, we avoid it here */
if($_GET['action'] == 'get_products'){
/* We're here to get the product listing...
You can obviously change this file to include many
different actions based on the request.
*/
switch($_GET['id']){
/* We had the following in our list.
0 Audio
1 Games
2 Internet
The integer value on the left is the value
corresponding to the javascript selectedIndex
property.*/
case 0: // Audio Programs
/* Print HTML to fill the product_cage
Any output to the browser will be
retrieved in the XMLHttpRequest object's
responseText property */
echo '
<ul>
<li>CDex</li>
<li>CoolEdit</li>
<li>Winamp</li>
<li>XMMS</li>
</ul>';
break;
case 1: //Games
echo '
<ul>
<li>Blackjack</li>
<li>Calculatron</li>
<li>Hold\'em</li>
<li>Minesweeper</li>
<li>Tetris</li>
</ul>';
break;
case 2: //Internet
echo '
<ul>
<li>Epiphany</li>
<li>Internet Explorer</li>
<li>Mozilla</li>
<li>Netscape</li>
<li>Opera</li>
<li>Safari</li>
</ul>';
break;
default:
echo '<b>You didn\'t select an item from above!</b>';
break;
}
}
?>

0 引用