Php 如何在wordpress前端调用ajax

Php 如何在wordpress前端调用ajax,php,jquery,ajax,wordpress,Php,Jquery,Ajax,Wordpress,在我的插件文件夹中,我有两个文件 1.hello-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" />&nbsp

在我的插件文件夹中,我有两个文件 1.hello-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" />&nbsp; <!-- 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>
因此表单显示在前端,但在控制台中
未捕获引用错误:未定义提交

submit\u me()
在myajax.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
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调用中存在一些问题,所以建议我做错了什么,以及如何使它起作用……谢谢

确保函数
submit\u me()
未包含在
$(document.ready()
处理程序中。该函数在全局范围内不可见,因此无法从
onclick
属性调用

另外,在wordpress中包含脚本的正确方法是挂接
wp\u enqueue\u脚本
操作:

add_action('wp_enqueue_scripts', 'enqueue_your_scripts');
function enqueue_your_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' ) ) );

}

我想我应该提一下,这样别人就不会像我一样浪费两个小时了。 如果您尝试从前端使用ajax,但有一个插件可以禁用登录用户的管理员(后端)访问权限,那么就会出现问题。 为了解决这个问题,我从中获得了以下代码。 将其添加到functions.php中

if(isset($_REQUEST['action']) && $_REQUEST['action']=='AJAXfunctionCall'):
    do_action( 'wp_ajax_' . $_REQUEST['action'] );
endif;

其中AJAXfunctionCall是您的函数对Ajax调用的响应。

您是否有准备好的
处理程序?