要在ajax中使用外部脚本,必须注册一个操作来触发它。为此,您需要使用wp\\u ajax\\u YourAction和wp\\u ajax\\u nopriv\\u YourAction
add_action(\'wp_ajax_YourAction\', \'myAjaxFunction\');
// just a way to quickly print your js
add_action(\'wp_head\', \'print_js\');
function print_js(){
?><script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
action: \'YourAction\',
fun: \'42\',
};
$.post(ajaxurl, data, function(response) {
console.log(response);
var json = $.parseJSON(response);
alert(\'the fun number is\'+response.fun);
});
});
</script><?php
}
function myAjaxFunction(){
if(isset($_POST[\'fun\'])){
$action = $_POST[\'fun\'];
}
switch ($action) {
case \'fun\':
echo json_encode(array(\'fun\'=>$_POST[\'fun\']+1))
exit();
break;
default:
break;
}
这只是一个简单的示例,具体取决于您想如何触发ajax调用和要发布的数据。