繁体   English   中英

如何使用以下代码将 function() 中的数组返回到 wordpress ajax.php 上的 javascript:

[英]How return array in function() to javascript on wordpress ajax.php with following code:

这可能看起来很愚蠢,但我已经在里面呆了一个星期,帮帮我...

xhr dev-tools chrome 中的“响应”不会留下“0”,它永远不会返回我需要的数组......

从wordpress获取数据的Javascript代码

$(document).on("click", "[data-show-home-list-series]", function () {
                var id = $(this).attr("data-show-home-list-series");
                $("[data-show-home-list-series]").removeClass("active");
                $(this).addClass("active");
                var $list = $("#homeSliderSerieList");
                $.post("wp-admin/admin-ajax.php", { getHomeSliderSeries: id }, function (html) {
                    var data = jQuery.parseJSON(html);
                    if (data.status == "success") {
                        var listing = data.list;
                        var lister = [];
                        for (var i = 0; i < 20; i++) {
                            var row = listing[i];
                            lister.push(seriePoster(row.url, row.rating, row.poster, row.title, row.cat, row.episode));
                        }
                        $list.parent(".itemsList").addClass("fadingOut");
                        setTimeout(function () {
                            $list.html(lister.join(""));
                            $list.trigger("destroy.owl.carousel");
                            createItemSlider();
                            $list.parent(".itemsList").removeClass("fadingOut");
                        }, 200);
                    } else {
                        return false;
                    }
                });
            });

PHP 文件将数组 json 中的数据返回到 javascript 以 html 显示结果。

wp-admin/admin-ajax.php (theme/inc/core/ajax.php)


function getHomeSliderSeries(){
// i Want see that bellow in xhr response to javascript:    
//{"status":"success","list":{}}

}

add_action( 'wp_ajax_getHomeSliderSeries', 'getHomeSliderSeries' );
add_action( 'wp_ajax_nopriv_getHomeSliderSeries', 'getHomeSliderSeries' );

我的语言不是很好,希望你能理解,谢谢atentiton!!

您在$.post发送的数据缺少action属性。 这个属性负责告诉admin-ajax.php应该调用哪个注册到wp_ajax_{function_name}钩子的wp_ajax_{function_name}

action属性中的值应该与wp_ajax_{function_name}wp_ajax_nopriv_{function_name}中的function_name匹配才能被正确调用。

action属性与您要发送到后端的其他属性结合起来,以传递您需要发送的数据。

// Set the action and get the id.
var action = 'getHomeSliderSeries';
var id = $(this).attr("data-show-home-list-series");

// Create object to send data to backend.
// This must include an action property with 
// the name of the function on the backend.
var postData = {
  action: action,
  id: id,
  example: 'Send any data as a property. You can also nest objects and arrays.'
};

$.post("wp-admin/admin-ajax.php", postData, function(response) {
  if (response.status == "success") {
    console.log(response);
  }
}, 'json'); // Expect JSON from the backend. Now you don't need to parse.

现在在服务器端你的getHomeSliderSeries应该被调用。 现在可以通过全局$_POST变量及其相应的键访问所有其他属性(包括操作)。

对于响应,请使用要返回的数据创建关联数组。 这相当于 JavaScript 中的对象。 将数组编码为 JSON 并将其发送回。 现在前端应该看到一个对象作为响应。

function getHomeSliderSeries(){
  // Get the id from the post request.
  $id = isset($_POST['id']) ? $_POST['id'] : null;
  $example_string = isset($_POST['example_string']) ? $_POST['example_string'] : null;

  // Create an associative array for the response.
  $response = array(
    'status'   => 'success',
    'id'       => $id,
    'example'  => $example_string
  );

  // Return the array as a JSON string.
  return json_encode($response);

  // Cuts connection by stopping the function.
  die(); 
}

add_action( 'wp_ajax_getHomeSliderSeries', 'getHomeSliderSeries' );
add_action( 'wp_ajax_nopriv_getHomeSliderSeries', 'getHomeSliderSeries' );

在functions.php中尝试ajax回调函数

function swt_ajax_data() {
  $id = isset($_POST['id']) ? $_POST['id'] : '';

  // Create an associative array for the response.
  $responsedata = array(
   'id'       => $id,
  ); 
  $result = array();
  
  // if need featch the data from the template un comment the bellow five lines and commented the sixth line
  //ob_start();
  //include('templatepatj');
  //$opr_html .= ob_get_contents();
  //ob_get_clean();
  // $result['data'] = $opr_html;


  $result['data'] = $responsedata;// POST array data.
  }
  return wp_send_json_success($result);
  }
}

add_action('wp_ajax_swt_ajax_data', 'swt_ajax_data');
add_action('wp_ajax_nopriv_swt_ajax_data', 'swt_ajax_data');

本地化您的脚本并传递管理 ajax url

// Register the script
  wp_register_script( 'ajax-script', 'path/to/myscript.js' );
   // Localize the script with new data
   $js_array = array(
   'ajaxurl' => admin_url('admin-ajax.php'),
);
wp_localize_script( 'ajax-script', 'swtobj', $js_array );
// Enqueued script with localized data.
wp_enqueue_script( 'ajax-script' );

像下面一样尝试 Js。

$(document).on("click", "[data-show-home-list-series]", function () {
  var id = $(this).attr("data-show-home-list-series");
  $("[data-show-home-list-series]").removeClass("active");
  $(this).addClass("active");
  var $list = $("#homeSliderSerieList");

  var data = {
  'action': 'swt_ajax_data', 'id': id
  };
  $.ajax({
    url: swtobj.ajaxurl,
    type: 'POST',
    data: data,
    cache: false,
    dataType: 'json',
    success: function (response, textStatus, jqXHR) {
      var response_data = response.data.data;
      if (response_data != "" || response_data.length != 0) {
        console.log(response_data);
        // write your code here
      } else {
        // write your code here
      }
    },
  });
});

暂无
暂无

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

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