简体   繁体   English

WordPress的ajax没有在functions.php中调用函数

[英]Wordpress ajax is not calling function in functions.php

I wrote an ajax call in the front end. 我在前端写了一个ajax调用。 I wrote the server side in functions.php 我在functions.php中写了服务器端

function updateCont(){
    global $wpdb;
    $post_id = $_POST['post_id'];
    $key = $_POST['key'];
    $value = $_POST['value'];

    update_post_meta($post_id, $key, $value);
    echo $value;
    die();
}
add_action('wp_ajax_updateCont', 'updateCont');
add_action('wp_ajax_nopriv_updateCont', 'updateCont'); 

My jquery is as follows 我的jQuery如下

jQuery.ajax({
            type:"POST",
            url: "<?php echo admin_url('admin-ajax.php'); ?>",
            data: {"post_id":<?php echo get_the_ID();?>, "key":"top_left_content", "value":"new content"},
            success:function(data){
                console.log(data);// is 0
            }
        });

However, the data returned from the ajax call is always "0" When I searched for it, people say my function is not loaded into wordpress. 但是,从ajax调用返回的数据始终为“ 0”,当我搜索它时,人们会说我的函数未加载到wordpress中。 I don't understand what to do here. 我不明白该怎么办。

The worpress hook needs a action variable with the function name passed to the php Try: worpress钩子需要一个动作变量,其函数名传递给php Try:

   jQuery.ajax({
  type: "POST",
  url: "<?php echo admin_url('admin-ajax.php'); ?>",
  data: {
    action: 'updateCont',
    "post_id": <?php echo get_the_ID();?>,
    "key": "top_left_content",
    "value": "new content"

  },
  success: function (data) {
    console.log(data); // is new content
  }
});

You are missing "action": "updateCont" from your ajax data. 您的ajax数据中缺少"action": "updateCont" action specifies what WP ajax action you are targeting. action指定您要定位的WP ajax操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM