法典包括一个有用的页面AJAX in plugins 它概述了如何发送和接收ajax请求。
下面的代码介绍了在更改select字段并发出ajax请求时如何触发事件。确保获取并设置了nonce值。
/**
* Only execute after jQuery is loaded
*/
jQuery(document).ready(function ($) {
/**
* Trigger an event when the select field is changed.
*/
$( \'select[name="field_5481bc1472b1d"]\' ).change( function() {
/**
* The data you will send via ajax. Action
* needs to be a unique slug you will use
* to identify and respond to the call.
* An nonce will be needed to verify the
* authenticity of the call.
*/
var data = {
\'action\': \'customslug-action-name\',
\'selected\': $(this).val(),
\'nonce\': YOUR_NONCE_VALUE,
};
$.get( ajaxurl, data, function( r ) {
if ( r.success ) {
// do your thing
} else {
// there was some error
}
});
});
});
然后在服务器端,您将通过挂接到与您的操作相关联的经过身份验证和未经身份验证的ajax挂钩来接收和响应调用:
add_action( \'wp_ajax_customslug-action-name\', \'my_action_callback_for_logged_in_users\' );
add_action( \'wp_ajax_nopriv_customslug-action-name\', \'my_action_callback_for_logged_out_users\' );
确保您正在使用
check_ajax_referrer() 验证nonce。可以使用生成nonce
wp_nonce_field() 或者使用将其直接传递给JavaScript
wp_create_nonce.