【发布时间】:2014-01-11 06:39:14
【问题描述】:
在我的插件文件夹中,我有两个文件 1.你好ajax.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
所以表单显示在前端但在控制台Uncaught ReferenceError: submit_me is not defined
submit_me() 在 myajax.js 文件中定义为:
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 调用存在一些问题,所以请告诉我我做错了什么以及如何使它工作......谢谢
【问题讨论】:
-
你有
ready处理程序吗?