为什么不使用Wordpress ajax挂钩呢。这真的很简单。
首先从javascript或jQuery调用函数,将键用作“action”,将值用作“function hook name”
jQuery(document).ready(function($) {
var data = {
action: \'my_action\', // here is the function name
whatever: 1234 // if there are the data you want to pass
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
jQuery.post(ajaxurl, data, function(response) {
alert(\'Got this from the server: \' + response.first_name +\' \'+response.last_name);
});
});
然后需要创建ajax钩子函数。php
//wp_ajax is the prefix of the hooks and follow with your action name
add_action(\'wp_ajax_my_action\', \'my_action_callback\'); //this line is for logged in users
add_action(\'wp_ajax_nopriv_my_action\', \'my_action_callback\'); // this is for not logged in users
然后在这里编写自己的函数,并在函数中使用json格式返回结果。php就在ajax挂钩的下方或上方。
function my_action_callback(){
$data = array(
\'first_name\' => \'foo\',
\'last_name\' => \'bar\'
);
return json_encode($data);
die; // you need to die otherwise you will see extra zero in your result because Wordpress automatically insert zero to make sure you stop the function here
}
我希望你乐于使用这种方式。这很容易,也很快。
如果你想读更多http://codex.wordpress.org/AJAX_in_Plugins