WordPress implements AJAX requests in two situations: the AJAX request initiated by the foreground page and the AJAX request initiated by the background page.
In the data passed by Ajax, the action is a fixed field, and the value corresponding to the Action field must match the suffix in the hook name (the your_action_name part of the hook below). WordPress also takes this to differentiate between different AJAX requests.
1. Background AJAX Requests
Involves a hook:wp_ajax_ (your_action_name)
|
| Back-end PHP code for working with Ajax |
It is noteworthy that since the beginning of WordPress 2.8, the background interface has been automatically assigned a JS global variable ajaxurl, so in the above case, JS code can directly refer to this global variable as the request path of Ajax.
2. The foreground initiates an AJAX request
Involving another hook:wp_ajax_nopriv_ (Your_action_name)
Note: Unlike the situation 1, the front-end interface does not have a direct reference to the Ajaxurl, so you must pass a WordPress function Wp_localize_script () to pass the path variable through PHP to the front-end JS, for example:
|
| In this way, we read the object Test_ajax in the JS code Ajaxu |
The object variable Test_ajax here can only be accessed by the code in the corresponding JS file, which is the script.js in the above example.
|
| Back-end PHP code for working with Ajax |
WordPress Implements custom AJAX requests