如何在wordpress的前端调用ajax
在我的插件文件夹中,我有两个文件1. hello-ajax.php 2. myajax.js
并通过短代码我在前端添加此表单
This is where we\'ll get the response
在插件文件中,我添加了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); } ); }
但是这个function不起作用,而且据我所知,在ajax调用中存在一些问题,所以建议我做错了什么以及如何使它工作….谢谢
我想我应该提一下,这样有人可以避免像我一样浪费2个小时。 如果您从前端尝试ajax,但是您有一个禁用admin(后端)访问登录用户的插件,那么就会出现问题。 为了解决这个问题,我从everthere获得了以下代码。 将其添加到您的functions.php中
if(isset($_REQUEST['action']) && $_REQUEST['action']=='AJAXfunctionCall'): do_action( 'wp_ajax_' . $_REQUEST['action'] ); endif;
其中AJAXfunctionCall是响应Ajax调用的函数。
确保函数submit_me()
未包含在$(document).ready()
处理程序中。 该函数在全局范围内不可见,因此无法从onclick
属性调用。
此外,在wordpress中包含脚本的正确方法是挂钩到wp_enqueue_scripts
操作:
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' ) ) ); }