问题描述
在我的插件文件夹中,我有两个文件1. hello-ajax.php2. myajax.js
In my plugin folder I have two file 1. hello-ajax.php2. myajax.js
并通过简码将这个表单添加到前端
and by shortcode I add this form on frontend
<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文件添加为:
In plugin file I added js file as:
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
So form is displaying at front end but in console Uncaught ReferenceError: submit_me is not defined
submit_me()
在myajax.js文件中定义为:
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调用中存在一些问题,因此请向我建议我做错了什么以及如何使其起作用....谢谢
But this function is not working, and as far i know there is some problem in ajax call, so suggest me what did I wrong and how to make it work....Thanks
推荐答案
我应该提到这一点,以便有人可以避免像我一样浪费2个小时.如果您尝试从前端尝试Ajax,但您有一个插件无法对已登录的用户进行管理员(后端)访问,则存在问题.为了解决该问题,我从 everthere获得了以下代码.将此添加到您的functions.php
Thought I should mention this so someone can avoid wasting 2 hours like I did.If you are attempting ajax from the front end but you have a plugin that that disables admin (backend) access to logged in users then there is a problem.To solve, I got the following code from everthere.Add this to your functions.php
if(isset($_REQUEST['action']) && $_REQUEST['action']=='AJAXfunctionCall'):
do_action( 'wp_ajax_' . $_REQUEST['action'] );
endif;
其中AJAXfunctionCall是您响应Ajax调用的函数.
Where AJAXfunctionCall is your function responding to the Ajax call.
这篇关于如何在wordpress的前端调用ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!