1 回答
TA贡献1834条经验 获得超8个赞
在这里看一下我的一个插件中的一个有效的 ajax 示例。
Javascript 部分:
//setting click event on button click to fire a function
$('#YourButtonIdHere').click(function () {
YourFunctionNameHere();
});
//function to execute
function YourFunctionNameHere() {
//formdata variable consists of
//action: this is ajax action name for WordPress which we define in PHP with a callback function with same name. See in PHP code part.
//$('#YourFormIDHere').serialize(); //this gets content from form and serialize it.
var frm_data = "action=your_action_name_here&" + $('#YourFormIDHere').serialize();
$.ajax({
type: "POST",
url: ajaxurl, // since WordPress version 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
data: frm_data,
cache: false,
success: function(data, textStatus, jqXHR) {
//do stuff here in case of success
},
error: function(jqXHR, textStatus, errorThrown) {
//do stuff here in case of error
}
});
}
PHP部分:
//here wp_ajax is the required prefix for your custom actions
//first parameter is action name with wp_ajax prefix
//second parameter is callback function to execute with same name as your action
//for example if your action name is wp_ajax_save_settings then your callback will be save_settings
add_action( 'wp_ajax_your_action_name_here', 'your_action_name_here' );
function your_action_name_here() {
global $wpdb; // this is how you get access to the database
//do stuff here and echo response
echo "ajax call success";
wp_die(); // this is required to terminate immediately and return a proper response
}
- 1 回答
- 0 关注
- 112 浏览
添加回答
举报