1. Which two AJAX methods are available?
1.1. Official method
The main idea is:
Add wp_enqueue_script and wp_localize_script in functions to add the AJAX request address and call script. For example:
$ AJAX = array
(
'URL' => admin_url ('admin-ajax. Php '),
);
$ AJAXURL = get_bloginfo ('Template _ url'). '/public/js/Test_ajax.js ';
Wp_enqueue_script ('My-ajax-request', $ AJAXURL, array ('jquery '));
Wp_localize_script ('My-ajax-request', 'Ajax ', $ AJAX );
Function _ aaaa ()
{
$ Id = $ _ POST ['id'];
$ Json ['info'] = 'Rand = '. rand (0, $ id );
Header ("Content-Type: application/json ");
Echo json_encode ($ json );
Exit;
}
Add_action ('WP _ ajax_aaaa ',' _ aaaa '); // ajax for logged in users
Add_action ('WP _ ajax_nopriv_aaaa ',' _ aaaa '); // ajax for not logged in users
Of course, you can also do this:
$ AJAX = array
(
'URL' => admin_url ('admin-ajax. Php '),
);
$ AJAXURL = get_bloginfo ('Template _ url'). '/public/js/Test_ajax.js ';
Wp_enqueue_script ('My-ajax-request', $ AJAXURL, array ('jquery '));
Wp_localize_script ('My-ajax-request', 'Ajax ', $ AJAX );
Function _ aaaa ()
{
$ Id = $ _ POST ['id'];
$ Respond = 'Rand = '. rand (0, $ id );
Echo $ respond;
Die ();
}
Add_action ('WP _ ajax_aaaa ',' _ aaaa '); // ajax for logged in users
Add_action ('WP _ ajax_nopriv_aaaa ',' _ aaaa '); // ajax for not logged in users
1.2. Folk methods
This method is used to call related functions in functions by determining key parameters such as action during AJAX requests. For example:
Function _ bbbb ()
{
If ($ _ POST ['action'] = 'bbbbbb ')
{
$ Id = $ _ POST ['id'];
$ Json ['info'] = 'Rand = '. rand (0, $ id );
Header ("Content-Type: application/json ");
Echo json_encode ($ json );
Exit;
}
}
Add_action ('init ',' _ bbbb ');
You can also do this:
Function _ bbbb ()
{
If ($ _ POST ['action'] = 'bbbbbb ')
{
$ Id = $ _ POST ['id'];
$ Respond = 'Rand = '. rand (0, $ id );
Echo $ respond;
Die ();
}
}
Add_action ('init ',' _ bbbb ');
2. Efficiency of the two AJAX methods
Local network speed test results (sent data includes id and action, a small amount of data ):