如何在 Wordpress 中调用 ajax

Posted

技术标签:

【中文标题】如何在 Wordpress 中调用 ajax【英文标题】:How to call ajax in Wordpress 【发布时间】:2017-09-19 08:15:58 【问题描述】:

我的 ajax 调用输出总是显示 0,因为输出不知道为什么

functions.php我有这个代码

function get_data() 
    $abc = '1';
    $result = $wpdb->get_results("SELECT * FROM ".$wpdb->options ." WHERE option_name LIKE '_transient_%'");
    echo  $result; //returning this value but still shows 0
    wp_die();


add_action( 'wp_ajax_nopriv_get_data', 'get_data' );
add_action( 'wp_ajax_get_data', 'get_data' );

我的 ajax 调用是在 javascript

$('body').on("click", ".re-reset-btn", function(e)

    var panel = $('#re-compare-bar');       

    $.ajax(
             type : "GET",
             dataType : "json",
             url : "/wp-admin/admin-ajax.php",
             data : action: "get_data",
             success: function(response) 

                   alert("Your vote could not be added");
                   alert(response);
                
        );   

    $("#re-compare-bar-tabs div").remove(); 
    $('.re-compare-icon-toggle .re-compare-notice').text(0); 

);

我在没有使用插件的情况下在 wordpress 中进行 ajax 调用,但没有得到我正在传递的内容。即使我输出 $abc 仍然显示 0。

【问题讨论】:

查看这篇文章,演示和解释有关在前端和后端实现 AJAX 所需了解的一切:benmarshall.me/wordpress-ajax-frontend-backend @all 不错的答案,但也要考虑安全性.. nonce .. 【参考方案1】:

在后端有 WordPress 自己定义的全局 ajaxurl 变量。

这个变量不是 WP 在前端创建的。这意味着如果你想在前端使用 AJAX 调用,那么你必须自己定义这样的变量。

这样做的好方法是使用 wp_localize_script。

假设你的 AJAX 调用在 my-ajax-script.js 文件中,然后像这样为这个 JS 文件添加 wp_localize_script:

function my_enqueue() 
      wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/my-ajax-script.js', array('jquery') );
      wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
 
 add_action( 'wp_enqueue_scripts', 'my_enqueue' );

本地化你的 JS 文件后,你可以在你的 JS 文件中使用 my_ajax_object 对象:

jQuery.ajax(
    type: "post",
    dataType: "json",
    url: my_ajax_object.ajax_url,
    data: formData,
    success: function(msg)
        console.log(msg);
    
);

【讨论】:

它说 my_ajax_object 没有定义 wp_local_script 请将其替换为 wp_localize_script 现在我已经修改了代码【参考方案2】:

其实,WordPress 自带一个方便的功能来访问 admin-ajax。

要求

wp-admin中你不需要做任何事情,js库总是被加载

前端中,您需要将脚本wp-util 排入队列,如下所示:

add_action( 'wp_enqueue_scripts', 'my_enqueue_function' );

function my_enqueue_function()  
    // Option 1: Manually enqueue the wp-util library.
    wp_enqueue_script( 'wp-util' );

    // Option 2: Make wp-util a dependency of your script (usually better).
    wp_enqueue_script( 'my-script', 'my-script.js', [ 'wp-util' ] );

JS 库

wp-util 脚本包含可用于发出 ajax 请求的 wp.ajax 对象:

 wp.ajax.post( action, data ).done( okCallback ).fail( errCallback )

你的例子:

wp.ajax.post( "get_data",  )
  .done(function(response) 
    alert("Your vote could not be added");
    alert(response);
  );

PHP 代码

当然,您仍然需要在 PHP 脚本中创建 wp_ajax_* 挂钩。

add_action( 'wp_ajax_nopriv_get_data', 'my_ajax_handler' );
add_action( 'wp_ajax_get_data', 'my_ajax_handler' );

function my_ajax_handler() 
    wp_send_json_success( 'It works' );

提示:

对于 Ajax 响应,WordPress 提供了两个功能:

wp_send_json_success( $my_data )wp_send_json_error( $my_data ) - 两个函数都返回一个 JSON 对象并立即终止请求(即它们exit;

【讨论】:

我的主要问题是假设我已经发布了一个帖子数据,比如来自 jquery ajax 的电子邮件,那么可以说$email = $_POST['email'] 或者 Wordpress 有一些其他预定义的方法 感谢上帝的回答,上面的任何东西都不适合我 wp.ajax 在 localhost 中运行,但不在生产中你知道吗? @prk_001 请阅读“要求”部分并确保您的页面使用wp_enqueue_script( 'wp-util' );。这是一个 WordPress 核心脚本,提供 wp.ajax【参考方案3】:

使用admin_url('admin-ajax.php');添加admin-ajax.php

<script type="text/javascript">
    $('body').on("click", ".re-reset-btn", function(e)

        var panel = $('#re-compare-bar');

        $.ajax(
            type : "POST",
            dataType : "json",
            url : "<?php echo admin_url('admin-ajax.php'); ?>",
            data : action: "get_data",
            success: function(response) 
                alert("Your vote could not be added");
                alert(response);
            
        );

        $("#re-compare-bar-tabs div").remove();
        $('.re-compare-icon-toggle .re-compare-notice').text(0);

    );
</script>

【讨论】:

这段代码在一个javascript文件中......所以它没有运行 【参考方案4】:

我遇到了同样的问题。我是 WordPress 新手。因此,我在这里解释一下,以便每个新学习者都能了解 ajax 在 WordPress 中是如何调用的。

首先,在位于 wp-content/theme/selected_theme 文件夹下的 function.php 文件中创建一个函数。在这里,selected_theme 可能是您的主题名称。

在上面的问题中,创建了一个名为get_data()的函数;

    function get_data() 
        
        echo  "test";
        wp_die();  //die();
    

add_action( 'wp_ajax_nopriv_get_data', 'get_data' );
add_action( 'wp_ajax_get_data', 'get_data' );

在上面两行中,

    add_action 方法用于实现挂钩。在这里,我传递了两个参数,第一个是wp_ajax_nopriv_get_data。在这里,您可以将 get_data 替换为您的选择。而section参数是get_data,就是你要调用的函数名。 在第二个add_action中,我传递了两个参数,第一个是wp_ajax_get_data。在这里,您可以将 get_data 替换为您的选择。而section参数是get_data,就是你要调用的函数名。

这里,wp_ajax_nopriv 在用户未登录时调用,wp_ajax 在用户登录时调用。

jQuery.ajax(
    type: "post",
    dataType: "json",
    url: "/wp-admin/admin-ajax.php", //this is wordpress ajax file which is already avaiable in wordpress
    data: 
        action:'get_data' //this value is first parameter of add_action,
        id: 4
    ,
    success: function(msg)
        console.log(msg);
    
);

【讨论】:

【参考方案5】:
<form type="post" action="" id="newCustomerForm">

    <label for="name">Name:</label>
    <input name="name" type="text" />

    <label for="email">Email:</label>
    <input name="email" type="text" />

    <label for="phone">Phone:</label>
    <input name="phone" type="text" />

    <label for="address">Address:</label>
    <input name="address" type="text" />

    <input type="hidden" name="action" value="addCustomer"/>
    <input type="submit">
</form>
<br/><br/>
<div id="feedback"></div>
<br/><br/>

functions.php

wp_enqueue_script('jquery');

function addCustomer() 

    global $wpdb;

    $name = $_POST['name'];
    $phone = $_POST['phone'];
    $email = $_POST['email'];
    $address = $_POST['address'];

    if ( $wpdb->insert( 'customers', array(
        'name' => $name,
        'email' => $email,
        'address' => $address,
        'phone' => $phone
    ) ) === false ) 
        echo 'Error';
     else 
        echo "Customer '".$name. "' successfully added, row ID is ".$wpdb->insert_id;
    
    die();

add_action('wp_ajax_addCustomer', 'addCustomer');
add_action('wp_ajax_nopriv_addCustomer', 'addCustomer');

javascript

<script type="text/javascript">
jQuery('#newCustomerForm').submit(ajaxSubmit);

function ajaxSubmit() 
    var newCustomerForm = jQuery(this).serialize();

    jQuery.ajax(
        type: "POST",
        url: "/wp-admin/admin-ajax.php",
        data: newCustomerForm,
        success: function(data)
            jQuery("#feedback").html(data);
        
    );

    return false;

</script>

【讨论】:

【参考方案6】:

第 1 步:在必须添加其他 'wp_enqueue_script' 或 'wp_enqueue_style' 文件的函数文件中添加 ajax 'wp_enqueue_script' 文件

wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/my-ajax- script.js', array('jquery') );
    wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );

第 2 步:现在您需要使用 ajax 创建要获得响应的函数 例如下面

 add_action('wp_footer','add_ajaxex_in_footer');
   function add_ajaxex_in_footer()
     ?>

<script type="text/javascript">
    jQuery('#sbmtbtn').click(function()
    jQuery.ajax(
    type:"POST",
    url:my_ajax_object.ajax_url,
    data: action:'my_special_ajax_call_enroll_cours',
    success:function(res)
     console.log(res);
    
   );
  );</script><?php 
 

第 3 步:现在您必须创建要编写查询的函数,

add_action('wp_ajax_my_special_ajax_call_enroll_cours', 'enroll_cours');
add_action('wp_ajax_nopriv_my_special_ajax_call_enroll_cours', 'enroll_cours');

 function enroll_cours()
  
     echo "Here you van write Query or anything"; 
     exit;
 

=> 如果你想在 onClick 按钮之后触发 ajax 请求,只需传递按钮 ID

<input type="button" id="sbmtbtn" name="Save">

【讨论】:

【参考方案7】:

如果您在响应中收到0,则表示您的 ajax 调用工作正常。 但是,您尚未在函数 get_data 中将 $wpdb 定义为全局变量。 检查您的错误日志,您必须在那里看到错误。 试试:

function get_data() 
    global $wpdb;
    $abc = '1';
    $result = $wpdb->get_results("SELECT * FROM ".$wpdb->options ." WHERE option_name LIKE '_transient_%'");
    echo  $result; //returning this value but still shows 0
    wp_die();

【讨论】:

【参考方案8】:

这里如何在普通的 js 中制作 WordPress 中的 AJAX 调用。

var urlToajax=jsajaxe_S.ajaxurl;


function P_lifg() 

 var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() 
  if (this.readyState == 4 && this.status == 200) 
  document.getElementById("demo").innerHTML = this.responseText;
  document.getElementById("demo2").innerHTML = urlToajax+ "?action=testfirst";
  
;


  xmlhttp.open("GET", urlToajax+ "?action=testfirst", true);    
  xmlhttp.send(0);


See on this blog, what to add functions.php and template html to get this work, also reasonings why there is no data in vanilja js unlike jQuery, but just action

这里在functions.php中添加_actions:

add_action( 'wp_ajax_testfirst', __NAMESPACE__ .'\\FunctionTF' );       
add_action( 'wp_ajax_nopriv_testfirst', __NAMESPACE__ .'\\FunctionTF');

在上面添加这个函数,现在是这个函数:

 function FunctionTF()

 exit( "Hola hola" );
    
 

See explanation why? code in "exit" in my blog

这里在一些 wp-template 上添加这个 html

 <div id="demo"></div>
 <div id="demo2"></div>
 <button id="spesial_button" onclick="P_lifg()">I am spesial</button>

See rest in: https://praybook2.blogspot.com/2021/03/AJAX-plain-vanilla-js-wp-and-namespace.html

【讨论】:

以上是关于如何在 Wordpress 中调用 ajax的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Wordpress 中调用 ajax

如何在自定义 PHP 脚本中调用 WordPress 函数

如何在 Wordpress 插件中使用 jQuery 从 Iframe 调用 Iframe?

如何在wordpress中制作联系表格调用另一个php文件

wordpress contact-form-7 表单 代码如何调用?

如何在 Wordpress 中的 php 文件上调用 css? [复制]