【问题标题】:how to call ajax on frontend of wordpress如何在wordpress前端调用ajax
【发布时间】: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" />&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>

在插件文件中我添加了 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 处理程序吗?

标签: php jquery ajax wordpress


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    确保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' ) ) );
    
    }
    

    【讨论】:

      猜你喜欢
      • 2018-01-05
      • 1970-01-01
      • 2014-11-09
      • 1970-01-01
      • 2017-09-19
      • 2019-07-04
      • 1970-01-01
      • 1970-01-01
      • 2019-02-09
      相关资源
      最近更新 更多