在我的插件文件夹中,我有两个文件1。你好,阿贾克斯。php 2。myajax。js公司
通过快捷码,我将此表单添加到前端
<form id="theForm" method="post">
<input id="name" name="name" value = "name" type="text" />
<input name="action" type="hidden" value="the_ajax_hook" /> <!-- this puts the action the_ajax_hook into the serialized form -->
<input id="submit_button" value = "Click This" type="button" onClick="submit_me();" />
</form>
<div id="response_area">
This is where we\\\'ll get the response
</div>
在插件文件中,我将js文件添加为:
wp_enqueue_script( \'my-ajax-handle\', plugin_dir_url( __FILE__ ) . \'myajax.js\', array( \'jquery\' ) );
wp_localize_script( \'my-ajax-handle\', \'the_ajax_script\', array( \'ajaxurl\' => admin_url( \'admin-ajax.php\' ) ) );
// THE AJAX ADD ACTIONS
add_action( \'wp_ajax_the_ajax_hook\', \'the_action_function\' );
add_action( \'wp_ajax_nopriv_the_ajax_hook\', \'the_action_function\' ); // need this to serve non logged in users
// THE FUNCTION
function the_action_function(){
/* this area is very simple but being serverside it affords the possibility of retreiving data from the server and passing it back to the javascript function */
$name = $_POST[\'name\'];
echo"Hello World, " . $name;// this is passed back to the javascript function
die();// wordpress may print out a spurious zero without this - can be particularly bad if using json
}
// ADD EG A FORM TO THE PAGE
因此表单显示在前端,但在控制台中未捕获引用错误:未定义submit\\u me
submit_me() is defined in myajax.js file as:
function submit_me(){
//alert(a);
jQuery.post(the_ajax_script.ajaxurl, jQuery("#theForm").serialize()
,
function(response_from_the_action_function){
jQuery("#response_area").html(response_from_the_action_function);
}
);
}
但这个函数不起作用,据我所知,ajax调用中存在一些问题,所以请告诉我我做错了什么,以及如何使它起作用。
最合适的回答,由SO网友:helgatheviking 整理而成
在我看来,您的大多数代码都很好。您的脚本是否已加载?(通过查看页面源进行验证)。根据Milo的建议,这是如何将插件的脚本正确排队的方法:
// Enqueue your scripts
function load_my_scripts(){
wp_enqueue_script( \'my-ajax-handle\', plugin_dir_url( __FILE__ ) . \'myajax.js\', array( \'jquery\' ) );
wp_localize_script( \'my-ajax-handle\', \'the_ajax_script\', array( \'ajaxurl\' => admin_url( \'admin-ajax.php\' ) ) );
}
add_action( \'wp_enqueue_scripts\', \'load_my_scripts\' );
我不知道这是否会导致问题,但我可能会从使用
onclick
通过表单提交调用并触发ajax。将JS文件切换到以下位置:
jQuery(document).ready(function($){
$(\'#theForm\').submit(function(e){
$.ajax({
data: jQuery("#theForm").serialize(),
type: \'post\',
url: the_ajax_script.ajaxurl,
success: function(response_from_the_action_function) {
$("#response_area").html(response_from_the_action_function);
}
});
});
});