在这个基本的插件框架中,我试图获得ajax发送给wordpress admin ajax的数据。要由自定义函数处理的php。
从表单发送的数据似乎没有到达我的ea\\u ajax\\u handler()函数。它似乎到达了管理ajax。php(表单数据由jQuery收集,然后我得到一个200响应,用于管理ajax.php的post请求),但看起来它没有转发给ea\\u ajax\\u handler()。
以下是我的文件:
easyA。php:
/** Enqueue scripts */
add_action(\'wp_enqueue_scripts\', \'ea_scripts\');
function ea_scripts()
{
wp_enqueue_script(\'jquery\');
// easyA script in the footer
wp_register_script(\'easyA\', plugins_url(\'js/easyA.js\', __FILE__), array(\'jquery\'), \'\', true);
wp_enqueue_script(\'easyA\'); // wondering if it\'s really needed or if the previous line is enough...
wp_localize_script(\'easyA\', \'easyAVars\', array(\'ajaxUrl\' => admin_url(\'admin-ajax.php\')));
}
/** Shortcode to display form in pages / posts */
add_shortcode(\'easyA\',\'ea_display_form\');
function ea_display_form()
{
echo \'
<form id="eaForm">
<input type="text" name="username" />
<input type="submit" value="Submit" />
</form>
\';
}
/** Event handling */
add_action(\'wp_ajax_ea_ajax_handler\', \'ea_ajax_handler\');
add_action(\'wp_ajax_nopriv_ea_ajax_handler\', \'ea_ajax_handler\');
function ea_ajax_handler()
{
$json = array(
\'success\' => false,
\'result\' => 0
);
if (isset($_POST[\'username\'])) {
$result = \'Hi, \' . $_POST[\'username\'] . \'!\';
$json[\'success\'] = true;
$json[\'result\'] = $result;
}
echo json_encode($json);
wp_die();
}
easyA。js公司:
jQuery(document).ready(function($) {
$(\'#eaForm\').on(\'submit\', function() {
var that = $(this),
contents = that.serialize();
console.log(\'contents: \' + contents); // debugging
jQuery.ajax({
url: easyAVars.ajaxUrl,
dataType: \'json\',
type: \'post\',
data: contents,
action: \'ea_ajax_handler\', // function in easyA.php that will be triggered
success: function(data) {
console.log(data);
}
});
return false;
});
});