编辑“WordPress:AJAX in Plugin”
该编辑可以被撤销。 请检查下面的对比以核实您想要撤销的内容,然后发布下面的更改以完成撤销。
最后版本 | 您的文本 | ||
第1行: | 第1行: | ||
==Introduction== | ==Introduction== | ||
[[WordPress:AJAX|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. | [[WordPress:AJAX|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. | ||
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: | 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: | ||
* [[WordPress:AJAX|Ajax]] - Overview of the technology | * [[WordPress:AJAX|Ajax]] - Overview of the technology | ||
* [[WordPress:Writing a Plugin]] - How to write a plugin | * [[WordPress:Writing a Plugin]] - How to write a plugin | ||
* [[WordPress:Plugin API]] - Filters and actions - what they are and how to use them | * [[WordPress:Plugin API]] - Filters and actions - what they are and how to use them | ||
* 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 [[WordPress:Adding Administration Menus|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. | * 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 [[WordPress:Adding Administration Menus|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. | ||
* You will also need to know something about client-side JavaScript programming, PHP programming, and HTML, in order to use Ajax in WordPress. | * You will also need to know something about client-side JavaScript programming, PHP programming, and HTML, in order to use Ajax in WordPress. | ||
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). | 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 Implementation Basics == | == Ajax Implementation Basics == | ||
There are three steps in an Ajax request, in general: | There are three steps in an Ajax request, in general: | ||
# 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. | # 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. | ||
# 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. | # 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. | ||
# The returned information is displayed using JavaScript. | # The returned information is displayed using 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, [http://www.twilightuniverse.com/projects/sack/ 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. | 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, [http://www.twilightuniverse.com/projects/sack/ 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. | ||
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: | 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: | ||
* '''Request URL''': The URL on the server that will process the Ajax request. | * '''Request URL''': The URL on the server that will process the Ajax request. | ||
* '''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. | * '''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. | ||
* '''What to do if there is an error''': a JavaScript function to call if there is an Ajax error. | * '''What to do if there is an error''': a JavaScript function to call if there is an Ajax error. | ||
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 [http://www.twilightuniverse.com/projects/sack/ SACK Project Home Page], download the zip file, and read the documentation, because there are definitely other possibilities. | 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 [http://www.twilightuniverse.com/projects/sack/ SACK Project Home Page], download the zip file, and read the documentation, because there are definitely other possibilities. | ||
One other detail is that the PHP function that processes the Ajax request should use the PHP <tt>die</tt> function to pass back its JavaScript-encoded information. Example: <tt>die("javascript_commands_here")</tt> | One other detail is that the PHP function that processes the Ajax request should use the PHP <tt>die</tt> function to pass back its JavaScript-encoded information. Example: <tt>die("javascript_commands_here")</tt> | ||
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. | 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 on the Administration Side == | == Ajax on the Administration Side == | ||
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. | 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. | ||
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: | 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: | ||
<pre> | <pre> | ||
Latitude: <input type="text" name="latitude_field" /> | Latitude: <input type="text" name="latitude_field" /> | ||
第116行: | 第43行: | ||
Elevation: <input type="text" name="elevation_field" id="elevation_field" /> | Elevation: <input type="text" name="elevation_field" id="elevation_field" /> | ||
</pre> | </pre> | ||
Next, we need to define the JavaScript function <tt>myplugin_ajax_elevation</tt>, 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 <tt>admin_print_scripts</tt> action: | Next, we need to define the JavaScript function <tt>myplugin_ajax_elevation</tt>, 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 <tt>admin_print_scripts</tt> action: | ||
<pre> | <pre> | ||
第144行: | 第67行: | ||
<?php | <?php | ||
} // end of PHP function myplugin_js_admin_header | } // end of PHP function myplugin_js_admin_header | ||
</pre> | </pre> | ||
The next step is to fill in the body of the <tt>myplugin_ajax_elevation</tt> 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: | The next step is to fill in the body of the <tt>myplugin_ajax_elevation</tt> 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: <tt>(bloghome)/wp-admin/admin-ajax.php</tt>. 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". | * '''Request URL''': We're going to send our request to a special URL that is defined in the administration menu system of WordPress: <tt>(bloghome)/wp-admin/admin-ajax.php</tt>. 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". | ||
* '''Custom request variables''': We need to send the latitude and longitude to the server; we also need to send our "action" name to the <tt>admin-ajax.php</tt> 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. | * '''Custom request variables''': We need to send the latitude and longitude to the server; we also need to send our "action" name to the <tt>admin-ajax.php</tt> 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. | ||
Putting it all together, the body of the JavaScript function becomes: | Putting it all together, the body of the JavaScript function becomes: | ||
<pre> | <pre> | ||
function myplugin_ajax_elevation( lat_field, long_field, elev_field ) | function myplugin_ajax_elevation( lat_field, long_field, elev_field ) | ||
第203行: | 第93行: | ||
} // end of JavaScript function myplugin_ajax_elevation | } // end of JavaScript function myplugin_ajax_elevation | ||
</pre> | </pre> | ||
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 <tt>(bloghome)/wp-admin/admin-ajax.php</tt>, with an "action" parameter of "myplugin_elev_lookup". We'll use the <tt>wp_ajax_*</tt> action to tell WordPress which PHP function in our plugin to call when it receives this request. | 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 <tt>(bloghome)/wp-admin/admin-ajax.php</tt>, with an "action" parameter of "myplugin_elev_lookup". We'll use the <tt>wp_ajax_*</tt> action to tell WordPress which PHP function in our plugin to call when it receives this request. | ||
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: | 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: | ||
<pre> | <pre> | ||
add_action('wp_ajax_myplugin_elev_lookup', 'myplugin_ajax_elev_lookup' ); | add_action('wp_ajax_myplugin_elev_lookup', 'myplugin_ajax_elev_lookup' ); | ||
第279行: | 第135行: | ||
</pre> | </pre> | ||
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. | 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 on the Viewer-Facing Side == | == Ajax on the Viewer-Facing Side == | ||
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. | 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. | ||
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: | 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: | ||
<pre> | <pre> | ||
<form> | <form> | ||
第357行: | 第151行: | ||
</form> | </form> | ||
</pre> | </pre> | ||
Next, we need to define the JavaScript function <tt>myplugin_cast_vote</tt>, 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 <tt>wp_head</tt> action (you could also be a little more selective by using some of the <tt>is_xyz()</tt> [[WordPress:Conditional Tags]] tests): | Next, we need to define the JavaScript function <tt>myplugin_cast_vote</tt>, 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 <tt>wp_head</tt> action (you could also be a little more selective by using some of the <tt>is_xyz()</tt> [[WordPress:Conditional Tags]] tests): | ||
<pre> | <pre> | ||
第398行: | 第177行: | ||
</pre> | </pre> | ||
The next step is to fill in the body of the <tt>myplugin_cast_vote</tt> 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: | The next step is to fill in the body of the <tt>myplugin_cast_vote</tt> 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: | ||
* '''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 <tt>wp-content/plugins</tt> directory of WordPress. | * '''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 <tt>wp-content/plugins</tt> directory of WordPress. | ||
* '''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. | * '''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. | ||
Putting this together, the body of the JavaScript function becomes: | Putting this together, the body of the JavaScript function becomes: | ||
<pre> | <pre> | ||
function myplugin_cast_vote( vote_field, results_div ) | function myplugin_cast_vote( vote_field, results_div ) | ||
第469行: | 第198行: | ||
} // end of JavaScript function myplugin_cast_vote | } // end of JavaScript function myplugin_cast_vote | ||
</pre> | </pre> | ||
The final step in this example is to define what happens when the Ajax request gets to the server. This will go into the <tt>myplugin_ajax.php</tt> 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: | The final step in this example is to define what happens when the Ajax request gets to the server. This will go into the <tt>myplugin_ajax.php</tt> 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: | ||
<pre> | <pre> | ||
第535行: | 第232行: | ||
?> | ?> | ||
</pre> | </pre> | ||
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. | 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. | ||