我正在写一个插件。有一个按钮可以触发ajax请求,以执行我在插件页面中添加的操作:
我的插件PHP文件的标题:
add_action(\'wp_ajax_update_nav_items\', \'update_nav_items\' );
add_action(\'wp_ajax_nopriv_update_nav_items\', \'update_nav_items\' );
wp_enqueue_script( \'addItemToNav\', plugin_dir_url( __FILE__ ) . \'js/navFunctions.js\', array( \'jquery\', \'json2\' ) );
wp_localize_script( \'addItemToNav\', \'menuItems\', array(
// URL to wp-admin/admin-ajax.php to process the request
\'ajaxurl\' => admin_url( \'admin-ajax.php\' ),
// generate a nonce with a unique ID "myajax-post-comment-nonce"
\'postCommentNonce\' => wp_create_nonce( \'update_nav_items-nonce\' ),
\'action\' => \'update_nav_items\'
)
);
function update_nav_items() {
// Testing stuff
$response = json_encode( array( \'response\' => \'success\', \'html\' => \'some value\' ) );
ob_clean();
print_r( $response );
echo json_encode( $response );
die();
}
我的JavaScript触发:
var data = {
action: \'update_nav_items\',
postCommentNonce : menuItems.postCommentNonce,
menuitems: JSON.stringify(itemtest)
};
jQuery.ajax({
url: menuItems.ajaxurl,
data: data,
type: \'post\',
dataType: \'json\',
success: function( response ) {
console.log(response);
}
});
在浏览器控制台中,将请求发送到正确的url,包括以下参数:
action update_nav_items
menuitems {"glossary":{"title":"example glossary","GlossDiv":{"title":"S","GlossList":{"GlossEntry":{"ID":"SGML","SortAs":"SGML","GlossTerm":"Standard Generalized Markup Language","Acronym":"SGML","Abbrev":"ISO 8879:1986","GlossDef":{"para":"A meta-markup language, used to create markup languages such as DocBook.","GlossSeeAlso":["GML","XML"]},"GlossSee":"markup"}}}}}
postCommentNonce 0cee7325b3
(menuitems仅用于使用正确的JSON进行测试)
我得到的是response is 0, 因此,行动似乎存在问题。我就是找不到。我已经尝试在我的函数中添加操作。php,它仍然不起作用。
有人有线索吗?