The main advantages of using this file for Ajax are as follows:
Security: WordPress performs complicated security optimization. If we write it on our own, it is a waste of time and resources.
Compatible. Because files are public, generic hooks are provided, and other plug-ins can be involved.
High efficiency. This does not explain. It not only conforms to the principle (the init hook is executed), but also takes into account the efficiency problem.
Convenience: a hook can output code without any judgment conditions.
I checked it online and found that there was not much information about the file. So I looked at the source code and found that it was actually very simple to use.
First, request this file:
The code is as follows: |
Copy code |
Echo admin_url ('admin-ajax. Php '); |
When sending a request to the admin-ajax.php, there is a required parameter that is action, because the admin-ajax.php needs to trigger different hooks based on whether the user has logged in
The code is as follows: |
Copy code |
// If you do not log on, the hook is triggered. Do_action ('WP _ ajax_nopriv _ '. $ _ REQUEST ['action']); // If you log on, this hook is triggered. Do_action ('WP _ ajax _ '. $ _ POST ['action']); The code for sending an Ajax request is roughly as follows: JQuery. post ( MyAjax. ajaxurl, { Action: 'myajax-submit ', PostID: MyAjax. postID }, Function (response ){ Alert (response ); } ); |
Now, we only need to process Ajax requests in our topic file, and do not need to process them in a separate file.
The code is as follows: |
Copy code |
Add_action ('WP _ ajax_nopriv_myajax-submit ', 'myajax _ submit '); Add_action ('WP _ ajax_myajax-submit ', 'myajax _ submit '); Function myajax_submit (){ $ PostID = $ _ POST ['postid']; $ Response = json_encode (array ('success '=> true )); Header ("Content-Type: application/json "); Echo $ response; // This is critical. Do not forget "exit" Exit; } |
Yes, the wp_ajax_nopriv_action parameter content and wp_ajax_action parameter content will be called respectively in the login and not login, so here the output can be, the specific can be studied under the admin-ajax.php file.