WordPress:AJAX in Plugin
Introduction[ ]
介绍[ ]
Ajax (Asynchronous JavaScript And XML) is a technology that allows a web page to update some of its information without a full page reload. It is used in the Administration sections of WordPress for auto-save of post edits, adding new categories, and other purposes. Some WordPress WordPress:Plugins also use AJAX for things like voting on post ratings and map refreshes.
Ajax (异步 JavaScript 和 XML)是种技术,网页不需要载入整个页面,就可以更新一些信息。这种技术用在WordPress的管理部分,用来自动保存文章编辑内容,添加新的类别,以及其它用途。一些WordPress插件也使用AJAX,用于,如,对网页级别进行投票和更新地图。
This article, aimed at plugin developers, describes how to add Ajax to a plugin. Before reading this article, you should be familiar with the following:
本篇文章针对的是插件开发人员,描述了怎样将Ajax添加到插件上。阅读这篇文章之前,你应该熟悉:
- Ajax - Overview of the technology
- Ajax –技术概述
- WordPress:Writing a Plugin - How to write a plugin
- 编写插件 – 怎样编写插件
- WordPress:Plugin API - Filters and actions - what they are and how to use them
- 插件API - Filters and actions –为什么是这样的,以及怎样使用
- How to add HTML to the appropriate WordPress page, post, or screen -- for instance, if you want to add Ajax to administration screens you create, you will need to understand how to add administration menus to WordPress; if you want to add Ajax to the display of a single post, you'll need to figure out the right filters and actions to add HTML to that spot on viewer-facing blog screens. This article does not cover these topics.
- 怎样将HTML添加到适当的WordPress页面,文章或者界面—例如,如果你想要将Ajax添加到你创建的管理界面,你就要明白怎样将管理菜单添加到WordPress;如果你想要将Ajax添加到显示的一篇文章中,你需要了解使用恰当的filters和actions,将HTML添加到访客浏览的博客界面的网页上。本篇文章不涉及这些话题。
- You will also need to know something about client-side JavaScript programming, PHP programming, and HTML, in order to use Ajax in WordPress.
- 你也需要知道关于用户区JavaScript,PHP程序设计和HTML的相关内容,便于在WordPress中使用Ajax。
It turns out that the techniques for adding Ajax to a plugin are quite different, depending on whether you want the Ajax functionality to be part of the WordPress administration screens, or to appear on the viewer-facing side of WordPress. So, this article treats those two possibilities separately (after discussing common considerations).
根据你是将Ajax功能添加为WordPress管理界面的一部分,还是添加到WordPress访客界面,将Ajax添加到插件的方法,差别很大。因此,这篇文章分别产生了这两种情况(讨论了一般的情况之后)。
Ajax Implementation Basics[ ]
运行Ajax 基本知识[ ]
There are three steps in an Ajax request, in general:
一般情况下,Ajax请求,有三个步骤:
- The user does something (such as clicking or dragging the mouse), and JavaScript embedded in the HTML of the web page responds by composing a "request" and sending it to a special URL on the web server. Due to security restrictions, the URL the request goes to must be on the same web site that the file containing the JavaScript came from.
- 用户执行一些操作(如点击或者拖拉鼠标),嵌套在网页HTML中的JavaScript就会创建"请求"并且发送到网页服务器上特别的URL中。出于安全考虑,进入的URL请求必须与包含JavaScript的文件位于同一个站点。
- A script or program on the web server (in WordPress, this will generally be one or more PHP functions) processes the request and sends information back to the browser.
- 网络服务器上的脚本或者程序(在WordPress中,是一个或者多个PHP函数)处理请求并且将信息发送回浏览器。
- The returned information is displayed using JavaScript.
- 使用JavaScript显示返回的信息。
Unfortunately, much of Ajax is JavaScript, which runs in the user's web browser, and the different web browsers have not all implemented the Ajax calls and responses in the same manner. So, to make things easier, most Ajax developers choose to use a tested cross-browser library that wraps the particular browser idiosyncracies in a standard class with a documented API. In this article, we'll use one such library, SACK (Simple Ajax Code-Kit), which is included in WordPress. We'll need to make sure both the SACK library and the JavaScript functions that compose the Ajax request get included in the HTML head section of the web page where the Ajax request will take place; the sections below will show how to do that for both the administration and viewer-facing sides of WordPress.
不幸地是,大多数Ajax是JavaScript,在用户浏览器中运行,不同的浏览器执行Ajax调用与回应的方式不同。因此,要使得操作更为简单,Ajax开发人员选择使用已经在多个浏览器中测试的,包括了标准级别的特别的浏览器的特点的,已归档的API。在这篇文章中,我们会使用这样的浏览器集, SACK (简单的 Ajax Code-Kit),包含在WordPress中。我们需要确定创建Ajax请求的SACK集和JavaScript函数都包含在网页的HTML标头部分,Ajax会在这里产生;下面的部分将会显示怎样为WordPress管理界面和访客界面执行这个操作。
When creating an Ajax request using the SACK library, we'll need to supply the following information; the sections below will fill in the details of what this information should be for the administration side and the viewer-facing side:
使用SACK集创建Ajax请求的时候,我们需要支持以下的信息;下面的部分解释了对于管理界面和访客界面,这个信息分别是什么:
- Request URL: The URL on the server that will process the Ajax request.
- 请求URL:服务器上的URL会处理Ajax请求。
- Custom request variables: SACK allows us to set arbitrary request variables, which are sent via POST or GET to the server. Cookie information can also be sent.
- 自定义请求变数:SACK使我们设置任意的请求变数,通过POST或者GET发送到服务器。也可以发送Cookie信息。
- What to do if there is an error: a JavaScript function to call if there is an Ajax error.
- 如果只有一个错误,怎么办:如果有个Ajax错误,调用JavaScript函数。
By default, SACK assumes that the returned information from the server is JavaScript code, which is executed when it comes in (asynchronously). In the examples below, we'll use this default behavior, so the PHP functions that are processing Ajax requests will need to compose their results into JavaScript commands. If you want to do something else with the returned information in your plugin, you might want to visit the SACK Project Home Page, download the zip file, and read the documentation, because there are definitely other possibilities.
默认情况下,SACK假定从服务器中返回的信息是JavaScript代码,进入的时候(不同时),这个代码就会得到执行。在下面的例子中,我们会使用这个默认操作,这样处理Ajax请求的PHP函数就需要将结果创建为JavaScript命令。如果你希望使用插件中返回的信息执行另外一些操作,你可能想要访问SACK Project 主页,下载压缩文件,阅读文章,因为的确有其它的可能情况。
One other detail is that the PHP function that processes the Ajax request should use the PHP die function to pass back its JavaScript-encoded information. Example: die("javascript_commands_here")
另外一个详细信息就是处理Ajax请求的PHP函数必须使用PHP die函数,返回JavaScript编码的信息。例如:die("javascript_commands_here")
With this common Ajax background in mind, the next two sections go through examples of how to use Ajax on the administration screens of WordPress, and on the viewer-facing side of WordPress. The two sections are independent, so you can just read the one that is appropriate for your plugin, if you want.
有个这个普通的Ajax背景知识之后,下面的两个部分,介绍了怎样在WordPress管理界面和访客界面上使用Ajax的例子。这两个部分是各自独立的,因此如果你想的话,可以阅读适合你的插件的其中的一个部分。
Ajax on the Administration Side[ ]
管理界面的Ajax[ ]
Since Ajax is already built into the core WordPress administration screens, adding more administration-side Ajax functionality to your plugin is fairly straightforward, and this section describes how to do it. As mentioned above, if you want to use Ajax on the blog-viewer-facing side of WordPress, you can completely skip this section of the article.
因为Ajax已经置入核心的WordPress管理界面,向你的插件添加更多的管理界面的Ajax功能,非常直接,这个部分阐述了怎样实现这个操作。如上所述,如果你希望在博客访客界面上使用Ajax,你完成可以跳过文章的这个部分。
As a simple example of using Ajax on the administration screens of a WordPress plugin, consider a geographical tagging plugin, where the user enters the latitude and longitude for a post, and the plugin will look up the elevation at that point, using a web service. Before we even think about Ajax programming, we need some fields on the screen where the user can enter the latitude and longitude, a button to look up elevation, and an elevation field to display the result. This article assumes you already know how to add these to the appropriate screen, and can adjust field widths, text, styles, etc. to your liking; you'll want to add something like this, inside an HTML form in the admin screens:
举一个在WordPress管理界面中使用Ajax的一个简单的例子,如一个geographical 标签插件,用户在这个插件中输入文章的 latitude 和 longitude ,插件就会使用网页服务,查找文章的elevation。考虑Ajax程序之前,在界面上我们需要一些栏,用户可以在这些栏中输入latitude 和longitude,还要有个按钮查找 elevation,还有个elevation栏显示结果。这篇文章假定你已经知道了怎样将这些栏添加到适当的界面,而且能够根据你的喜好,调整栏的宽度,文本,样式,等等;你可能想将这些内容,添加到管理界面中的HTML样式中:
Latitude: <input type="text" name="latitude_field" /> Longitude: <input type="text" name="longitude_field" /> <input type="button" value="Look Up Elevation" onclick="myplugin_ajax_elevation(this.form.latitude_field,this.form.longitude_field,this.form.elevation_field);" /> Elevation: <input type="text" name="elevation_field" id="elevation_field" />
Latitude: <input type="text" name="latitude_field" /> Longitude: <input type="text" name="longitude_field" /> <input type="button" value="Look Up Elevation" onclick="myplugin_ajax_elevation(this.form.latitude_field,this.form.longitude_field,this.form.elevation_field);" /> Elevation: <input type="text" name="elevation_field" id="elevation_field" />
Next, we need to define the JavaScript function myplugin_ajax_elevation, the onClick action for the button, which will read the information the user entered, compose a request with SACK, and send it to the plugin for processing. As mentioned in the previous section, this JavaScript function and the SACK library need to get added to the HTML head section of the administration screen in question; the easiest way to do that is to add it to all admin screens using the admin_print_scripts action:
接着,我们需要定义JavaScript函数myplugin_ajax_elevation,按钮的onClick action,会阅读用户输入的信息,使用SACK创建请求,并且将请求发送到插件,等待处理。如先前部分所描述的,这个JavaScript函数和SACK集需要添加到正在讨论的管理界面的HTML标头部分;最简单的方法就是使用admin_print_scripts action,将其添加到所有的管理界面:
add_action('admin_print_scripts', 'myplugin_js_admin_header' ); function myplugin_js_admin_header() // this is a PHP function { // use JavaScript SACK library for Ajax wp_print_scripts( array( 'sack' )); // Define custom JavaScript function ?> <script type="text/javascript"> //<![CDATA[ function myplugin_ajax_elevation( lat_field, long_field, elev_field ) { // function body defined below } // end of JavaScript function myplugin_ajax_elevation //]]> </script> <?php } // end of PHP function myplugin_js_admin_header
add_action('admin_print_scripts', 'myplugin_js_admin_header' ); function myplugin_js_admin_header() //这是个PHP函数 { // 为Ajax使用JavaScript SACK 集 wp_print_scripts( array( 'sack' )); // 定义自定义的JavaScript函数 ?> <script type="text/javascript"> //<![CDATA[ function myplugin_ajax_elevation( lat_field, long_field, elev_field ) { // 函数主体在下面定义了 } // JavaScript 函数 myplugin_ajax_elevation的结尾部分 //]]> </script> <?php } // PHP 函数myplugin_js_admin_header的结尾部分
The next step is to fill in the body of the myplugin_ajax_elevation JavaScript function, which is supposed to read the latitude and longitude from the form fields, compose an Ajax request with SACK, and send the request to the server. Given the list of generic SACK information from the previous section, here is what we need to set up for this example:
- Request URL: We're going to send our request to a special URL that is defined in the administration menu system of WordPress: (bloghome)/wp-admin/admin-ajax.php. Below, we'll see how to add a special Ajax action to WordPress that will tell that script which plugin PHP function to call when the request is received. For our purposes, let's assume the action is called "myplugin_elev_lookup".
其次是要添加myplugin_ajax_elevation JavaScript 函数的主题部分,这个函数应用从表格栏中读出latitude 和 longitude ,使用SACK创建Ajax请求,并且将请求发送到服务器。给出前部分的一般的SACK信息列表,下面是我们需要为这个例子,设置的内容:
* 请求的 URL: 我们将要将我们的请求发送了一个特别的URL,这个URL定义在WordPress管理菜单系统: (bloghome)/wp-admin/admin-ajax.php。在下面,我们会了解怎样将特别的Ajax添加到WordPress,会通知脚本,收到请求的时候,调用哪个插件PHP函数。鉴于我们的目的,我们假定action称为"myplugin_elev_lookup"。
- Custom request variables: We need to send the latitude and longitude to the server; we also need to send our "action" name to the admin-ajax.php script. We also need to send the current page's cookies, since they contains the login information. And finally, since our server-side function will need to return JavaScript to display the results, we'll need to pass the ID of the elevation field into our function.
- 自定义请求变数:我们需要将latitude和longitude发送到服务器;我们也需要将我们的"action"名发送到admin-ajax.php脚本。我们也需要发送当前网页的cookies,因为这些cookies包含有登录信息。最后,因为我们服务器方面的函数需要返回JavaScript显示结果,我们需要将elevation field的ID发送到我们的函数中。
Putting it all together, the body of the JavaScript function becomes:
将所有总结,JavaScript函数的主体成为:
function myplugin_ajax_elevation( lat_field, long_field, elev_field ) { var mysack = new sack( "<?php bloginfo( 'wpurl' ); ?>/wp-admin/admin-ajax.php" ); mysack.execute = 1; mysack.method = 'POST'; mysack.setVar( "action", "myplugin_elev_lookup" ); mysack.setVar( "latitude", lat_field.value ); mysack.setVar( "longitude", long_field.value ); mysack.setVar( "elev_field_id", elev_field.id ); mysack.encVar( "cookie", document.cookie, false ); mysack.onError = function() { alert('Ajax error in looking up elevation' )}; mysack.runAJAX(); return true; } // end of JavaScript function myplugin_ajax_elevation
function myplugin_ajax_elevation( lat_field, long_field, elev_field ) { var mysack = new sack( "<?php bloginfo( 'wpurl' ); ?>/wp-admin/admin-ajax.php" ); mysack.execute = 1; mysack.method = 'POST'; mysack.setVar( "action", "myplugin_elev_lookup" ); mysack.setVar( "latitude", lat_field.value ); mysack.setVar( "longitude", long_field.value ); mysack.setVar( "elev_field_id", elev_field.id ); mysack.encVar( "cookie", document.cookie, false ); mysack.onError = function() { alert('Ajax error in looking up elevation' )}; mysack.runAJAX(); 返回正确的; } // JavaScript函数 function myplugin_ajax_elevation的结尾部分
The final step in this example is to define what happens when the Ajax request gets to the server. As mentioned above, we are sending the request to (bloghome)/wp-admin/admin-ajax.php, with an "action" parameter of "myplugin_elev_lookup". We'll use the wp_ajax_* action to tell WordPress which PHP function in our plugin to call when it receives this request.
这个例子中的最后一个操作设置确定Ajax请求进入服务器的时候,发生了什么,我们将请求发送到(bloghome)/wp-admin/admin-ajax.php,使用"myplugin_elev_lookup"的"action"参数。我们会使用wp_ajax_* action告诉WordPress,当WordPress收到请求的时候,会调用我们插件中的哪个PHP函数。
Our PHP function will need to send the latitude and longitude to the elevation lookup server, wait for a response, parse the result, and send the information back as JavaScript commands. We'll use the "Snoopy" web request PHP class (built into WordPress) to send the web request. Here's how to do it:
我们的PHP函数需要将latitude和 longitude发送到elevation查找服务器,等待响应,解析结构,再将信息作为JavaScript命令发送回。我们将要使用"Snoopy"网络请求PHP class(置入WordPress)发送网络请求。下面是操作方式:
add_action('wp_ajax_myplugin_elev_lookup', 'myplugin_ajax_elev_lookup' ); function myplugin_ajax_elev_lookup() { // read submitted information $lat = $_POST['latitude']; $long = $_POST['longitude']; $field_id = $_POST['elev_field_id']; $units = "FEET"; // Build Snoopy URL request require_once( ABSPATH . WPINC . '/class-snoopy.php' ); $sno = new Snoopy(); $sno->agent = 'WordPress/' . $wp_version; $sno->read_timeout = 2; $reqURL = "http://gisdata.usgs.gov/XMLWebServices/TNM_Elevation_Service.asmx/getElevation?Y_Value=$lat&X_Value=$long&Elevation_Units=$units&Source_Layer=-1&Elevation_Only=1"; // Send request to elevation server if( !$sno->fetchtext( $reqURL )) { die( "alert('Could not connect to lookup host.')" ); } // Parse response if( !preg_match("|<Elevation>([\d.-]+)</Elevation>|",$sno->results)){ die( "alert('Could not find elevation in lookup results.')" ); } $matches=preg_split( "|<Elevation>([\d.-]+)</Elevation>|",$sno->results); //REGEX BUG: but it'll return info // Compose JavaScript for return die( "document.getElementById('$field_id').value = " . $matches[1] ); } // end of myplugin_axax_elev_lookup function
add_action('wp_ajax_myplugin_elev_lookup', 'myplugin_ajax_elev_lookup' ); function myplugin_ajax_elev_lookup() { //阅读递交的信息 $lat = $_POST['latitude']; $long = $_POST['longitude']; $field_id = $_POST['elev_field_id']; $units = "FEET"; // 设置Snoopy URL请求 require_once( ABSPATH . WPINC . '/class-snoopy.php' ); $sno = new Snoopy(); $sno->agent = 'WordPress/' . $wp_version; $sno->read_timeout = 2; $reqURL = "http://gisdata.usgs.gov/XMLWebServices/TNM_Elevation_Service.asmx/getElevation?Y_Value=$lat&X_Value=$long&Elevation_Units=$units&Source_Layer=-1&Elevation_Only=1"; // 将请求发送到elevation 服务器 if( !$sno->fetchtext( $reqURL )) { die( "alert('不能够连接到查找服务器')" ); } // 解析结果 if( !preg_match("|<Elevation>([\d.-]+)</Elevation>|",$sno->results)){ die( "alert('Could not find elevation in lookup results.')" ); } $matches=preg_split( "|<Elevation>([\d.-]+)</Elevation>|",$sno->results); //REGEX BUG: but it'll return info // 创建JavaScript返回 die( "document.getElementById('$field_id').value = " . $matches[1] ); } // end of myplugin_axax_elev_lookup function
That's it! You will need to add a few details, such as error checking and verifying that the request came from the right place, but hopefully the example above will be enough to get you started on your own administration-side Ajax plugin.
就这么多了!你需要添加一些详细信息,如错误检查,确认请求来自正确的地点,但是希望上述的例子,能够充分地帮助你开始处理你自己管理界面的Ajax插件。
Ajax on the Viewer-Facing Side[ ]
访客界面的Ajax[ ]
Implementing Ajax on the viewer-facing side of a WordPress site is slightly more ad-hoc than doing Ajax on the administration side, because WordPress itself doesn't have viewer-facing Ajax built in, but it's not too bad, and this section describes how to do it. As mentioned above, if you want to use Ajax on the administration side of WordPress, you can completely skip this section of the article.
在WordPress站点的访客界面执行Ajax比在管理界面执行,要稍微特别,因为WordPress本身没有内置的访客界面的Ajax,但是这并不坏,这个部分描述了怎样操作。如上所述,如果你想要在WordPress管理界面使用Ajax,你可以完成地跳过文章的这个部分。
As an example, let's consider a plugin that allows a blog viewer to vote on or rate something (which could be a generic poll plugin, a post rating plugin, or something else like that). When the blog viewer submits a vote, we want the submission to go via Ajax, so that the viewer doesn't have to wait for the page to refresh; after the vote is registered, we'll want to update the running vote total display. For this example, we'll assume the voting and display are text-based, for simplicity, and we'll assume you've either edited the theme or used a WordPress filter or action to add HTML to the appropriate WordPress viewer-facing screen. The added HTML will look something like this:
作为例子,假如插件能够使得博客访问投票或者给某个东西排名(可能是一般的投票插件,文章级别插件或者其它类似的插件)。当博客访客递交了投票后,我们希望投票通过Ajax递交,这样访客不需要等待网页刷新;投票递交之后,我们想要更新总共显示的投票数目。在这个例子中,我们假定是以文本为基础显示投票的,这样更简单,我们假定你编辑了主题或者使用WordPress filter或者action,将HTML添加到适当的WordPress访客界面。添加的HTML可能看起来像:
<form> Your vote: <input type="text" name="uservote" /> <input type="button" value="Vote!" onclick="myplugin_cast_vote(this.form.uservote,'voteresults');" /> <div id="voteresults"> (previous results output from your PHP function) </div> </form>
<form> 你的投票: <input type="text" name="uservote" /> <input type="button" value="Vote!" onclick="myplugin_cast_vote(this.form.uservote,'voteresults');" /> <div id="voteresults"> (来自你的PHP函数,输出先前的结果) </div> </form>
Next, we need to define the JavaScript function myplugin_cast_vote, the onClick action for the button, which will read the information the user entered, compose a request with SACK, and send it to the plugin for processing. As mentioned in the introductory section, this JavaScript function and the SACK library need to get added to the HTML head section of the web page the user is viewing. One way to do that is to add it to all viewer-facing screens using the wp_head action (you could also be a little more selective by using some of the is_xyz() WordPress:Conditional Tags tests):
其次,我们需要定义JavaScript函数myplugin_cast_vote,按钮的onClick action,会阅读用户输入的信息,使用SACK创建请求,并且将请求发送到插件,等待处理。如介绍部分所提到的,这个JavaScript函数和SACK集需要添加到用户浏览的网页的HTML标头部分。一种方式是使用wp_head action将其添加到所有的访客界面(使用一些is_xyz() 条件式标签测试,你可以拥有更多的选择):
add_action('wp_head', 'myplugin_js_header' ); function myplugin_js_header() // this is a PHP function { // use JavaScript SACK library for Ajax wp_print_scripts( array( 'sack' )); // Define custom JavaScript function ?> <script type="text/javascript"> //<![CDATA[ function myplugin_cast_vote( vote_field, results_div ) { // function body defined below } // end of JavaScript function myplugin_cast_vote //]]> </script> <?php } // end of PHP function myplugin_js_header
add_action('wp_head', 'myplugin_js_header' ); function myplugin_js_header() // 这是个PHP函数 { // 为Ajax使用JavaScript SACK集 wp_print_scripts( array( 'sack' )); //定义自定义的 JavaScript 函数 ?> <script type="text/javascript"> //<![CDATA[ function myplugin_cast_vote( vote_field, results_div ) { // 下面定义了函数主体 } // JavaScript 函数 myplugin_cast_vote的结尾部分 //]]> </script> <?php } // PHP 函数 myplugin_js_header的结尾部分
The next step is to fill in the body of the myplugin_cast_vote JavaScript function, which is supposed to read the vote from the form field, compose an Ajax request with SACK, and send the request to the server. Given the list of generic SACK information from the introductory section, here is what we need to set up for this example:
下一步是要填写myplugin_cast_vote JavaScript函数的主体部分,这个函数应该会从表格栏中阅读票数,并且使用SACK创建Ajax请求,然后将请求返回到服务器。给出了介绍部分的一般的SACK信息列表,下面是我们需要为这个例子设置什么:
- Request URL: We need to send our request to a plugin PHP file. This could be the main plugin PHP file, or a separate PHP file. It's probably a little cleaner to do it in a separate file, which we'll assume is called "myplugin_ajax.php", located in the standard wp-content/plugins directory of WordPress.
- 请求 URL:我们需要将我们的请求发送到插件PHP文件。这可能是主要的插件PHP文件,或者分开的PHP文件。在分卡的文件中执行,可能更清晰,假如这个文件称为"myplugin_ajax.php",位于标准的WordPresswp-content/plugins目录。
- Custom request variables: We only need to send the vote and the ID of the div where the results go to the server, in this simple example.
- 自定义请求变数:在这个简单的例子中,我们只需要发送投票和投票结果进入服务器的div的ID。
Putting this together, the body of the JavaScript function becomes:
将这个放在一起,JavaScript函数的主体部分变为:
function myplugin_cast_vote( vote_field, results_div ) { var mysack = new sack( "<?php bloginfo( 'wpurl' ); ?>/wp-content/plugins/myplugin_ajax.php" ); mysack.execute = 1; mysack.method = 'POST'; mysack.setVar( "vote", vote_field.value ); mysack.setVar( "results_div_id", results_div ); mysack.onError = function() { alert('Ajax error in voting' )}; mysack.runAJAX(); return true; } // end of JavaScript function myplugin_cast_vote
function myplugin_cast_vote( vote_field, results_div ) { var mysack = new sack( "<?php bloginfo( 'wpurl' ); ?>/wp-content/plugins/myplugin_ajax.php" ); mysack.execute = 1; mysack.method = 'POST'; mysack.setVar( "vote", vote_field.value ); mysack.setVar( "results_div_id", results_div ); mysack.onError = function() { alert('Ajax error in voting' )}; mysack.runAJAX(); 返回正确的; } // JavaScript 函数myplugin_cast_vote的结尾部分
The final step in this example is to define what happens when the Ajax request gets to the server. This will go into the myplugin_ajax.php file, which will need to read the posted information, verify that the vote is valid, add the vote to the database, figure out what the new running totals are, and send that back to the browser. Leaving aside all the details of processing the vote, here's what needs to go into the file:
这个例子中的最后一个操作是,确定当Ajax请求进入服务器的时候,会发生什么。结果会进入myplugin_ajax.php文件,需要阅读已发表的信息,确定投票是有效的,将投票添加到数据库,确定新的投票总数,并且将结果发送到服务器。将处理投票过程放置一边,下面是需要输入文件的内容:
<?php // Put your author and license information here // TO DO! // Check request came from valid source here // TO DO! // read submitted information $vote = $_POST['vote']; $results_id = $_POST['results_div_id']; // Put your vote processing code here // In this example, assume // a) The processing code sets global // variable $error to a message if there is an error // b) If there is no error, $results contains // the HTML to put into the results DIV on the screen if( $error ) { die( "alert('$error')" ); } // Compose JavaScript for return die( "document.getElementById('$results_id').innerHTML = '$results'" ); ?>
<?php // 将你的作者和许可信息添在这里 // 操作! // 查看这里有效的请求 // 执行! // 阅读递交的信息 $vote = $_POST['vote']; $results_id = $_POST['results_div_id']; // 在这里放入你的投票过程代码 // 在这个例子中,假如,如果有错误, // a)处理代码将全局、 // 变数$error设置到message // b) 如果没错误, $results 包含 // HTML 放置到界面上的结果DIV if( $error ) { die( "alert('$error')" ); } // 从结果中创建JavaScript die( "document.getElementById('$results_id').innerHTML = '$results'" ); ?>
That's it! You will need to add a few details, such as error checking, escaping quotes, processing the vote, and verifying that the request came from the right place, but hopefully the example above will be enough to get you started on your own viewer-side Ajax plugin.
就这么多了!你需要添加一些详细信息,如错误检查,escaping quotes,处理投票,确认请求来自合适的位置,但是希望上面的例子能够使你开始处理你在自己的访客界面的Ajax插件。