Chuyển mảng javascript sang php ajax

Tôi có một hàm ajax kết nối với tệp php. Tôi đang cố gắng chuyển các đối số (‘tax_query’) được thu thập trên trang tới một truy vấn chạy trên php. Làm cách nào tôi có thể tạo một mảng (hoặc có thể chỉ là một chuỗi) trong javascript và chuyển nó làm đối số cho hàm bên trong php. Mọi thứ đều hoạt động ngoại trừ việc tôi có các đối số truy vấn trong tệp php được mã hóa cứng nơi tôi muốn chúng động dựa trên những gì tôi chuyển qua yêu cầu ajax

Đây là hàm jQuery của tôi lấy dữ liệu từ các lựa chọn của người dùng, lưu các biến và kết nối với php thông qua ajax

(function($) {

  function getFilters () {
    var filters = {}
    
    $('.checked').each(function () {
      filters[this.dataset.filter] = this.dataset.value
    })
    
      return filters
    }

    $(".dropdown-menu li a").click(function (event) {
      var $this = $(this)
      var $dropdown = $this.parents('.dropdown')
      var html = $this.text() + ' '
      
      $dropdown.find(".btn").html(html);  
      $dropdown.find('a').removeClass('checked');
      $this.addClass('checked');

      var filters = getFilters();

      //var level = filters["level"];
      var level = filters.level;
      var location = filters.location;
      var specialty = filters.specialty;
      
      alert("Level: "+level+" Location: "+location+" Specialty: "+specialty);

      console.log(getFilters());

      event.preventDefault();

      alert("made it up to ajax");
   
      $.ajax({
          type: 'POST',
          url: '',
          dataType: "html", // add data type
          data: { action : 'get_ajax_posts' },
          success: function( response ) {
              console.log( response );

              $( '.posts-area' ).html( response ); 
          }
      });      
    })

})(jQuery);

đây là hàm php của tôi chạy truy vấn bài đăng Wordpress và quay lại jquery

function get_ajax_posts() {
    // Query Arguments
    $args = array(
      'post_type' => 'the-talent',
      'tax_query' => array(
          'relation' => 'AND',
          array(
              'taxonomy' => 'level',
              'field'    => 'term_id',
              'terms'    => array( '25' ),// needs to be 3 and up? maybe use if statements?
          ),
          array(
              'taxonomy' => 'location',
              'field'    => 'term_id',
              'terms'    => array( '20' ),
          ),
          array(
              'taxonomy' => 'specialty',
              'field'    => 'term_id',
              'terms'    => array( '4' ),
          ),
          
      ),
    );

    // The Query
    $ajaxposts = new WP_Query( $args );

    $response = '';

    // The Query
    if ( $ajaxposts->have_posts() ) {
        while ( $ajaxposts->have_posts() ) {
            $ajaxposts->the_post();
            //$response .= get_template_part('products');

            $response .= 

            $name = get_field('name');
            $main_image = get_field('main_image');

         ?>

        

       

Cảm ơn vì sự giúp đỡ, nhưng tôi vẫn gặp sự cố…Tôi đã thử nhưng hiện tại phản hồi không có gì (tôi nghĩ)… đây là mã được cập nhật của tôi…

function get_ajax_posts() {

	$tax_query = ['relation' => 'AND'];

	foreach ($_POST['filters'] as $key => $value) {
	    $tax_query[] = [
	        'field' => 'term_id',
	        'taxononomy' => $key,
	        'terms' => [$value]
	    ];
	}

    // Query Arguments
    $args = array(
      'post_type' => 'the-talent',
      'tax_query' => $tax_query,
      // 'tax_query' => array(
      //     'relation' => 'AND',
      //     array(
      //         'taxonomy' => 'level',
      //         'field'    => 'term_id',
      //         'terms'    => array( '25' ),// needs to be 3 and up? maybe use if statements?
      //     ),
      //     array(
      //         'taxonomy' => 'location',
      //         'field'    => 'term_id',
      //         'terms'    => array( '20' ),
      //     ),
      //     array(
      //         'taxonomy' => 'specialty',
      //         'field'    => 'term_id',
      //         'terms'    => array( '4' ),
      //     ),
          
      // ),
    );

    // The Query
    $ajaxposts = new WP_Query( $args );

    $response = '';

    // The Query
    if ( $ajaxposts->have_posts() ) {
        while ( $ajaxposts->have_posts() ) {
            $ajaxposts->the_post();
            //$response .= get_template_part('products');

            $response .= 

            $name = get_field('name');
            $main_image = get_field('main_image');

         ?>

        

       

js

(function($) {


function getFilters () {
  var filters = {}
  
  $('.checked').each(function () {
    filters[this.dataset.filter] = this.dataset.value
  })
  
    return filters
  }

  $(".dropdown-menu li a").click(function (event) {
    var $this = $(this)
    var $dropdown = $this.parents('.dropdown')
    var html = $this.text() + ' '
    
    $dropdown.find(".btn").html(html);  
    $dropdown.find('a').removeClass('checked');
    $this.addClass('checked');

    var filters = getFilters();

    //var level = filters["level"];
    var level = filters.level;
    var location = filters.location;
    var specialty = filters.specialty;
    
    alert("Level: "+level+" Location: "+location+" Specialty: "+specialty);

    console.log(getFilters());


    event.preventDefault();

    alert("made it up to ajax");
 
    $.ajax({
        type: 'POST',
        url: '',
        dataType: "html", // add data type
       // data: { action : 'get_ajax_posts' },
        data: { action : 'get_ajax_posts' , filters: filters },
        success: function( response ) {
            console.log( response );

            alert("responce: "+response.toString() );

            $( '.posts-area' ).html( response ); 
        }
    });      
  })

})(jQuery);

Chuyển mảng javascript sang php ajax
m3g4p0p

Bạn có đang thực sự thêm bất kỳ dữ liệu nào vào $response nếu $ajaxposts->have_posts() không?

Tôi không thực sự chắc chắn làm thế nào để làm điều đó. Tôi đã thử thêm cái này nhưng vẫn nhận được null .. ngay cả khi tôi chuyển sang tax_query được mã hóa cứng đang hoạt động

echo var_dump($arg);

vì vậy ngay bây giờ mã được trả về phiên bản mã hóa cứng của tax_query

function get_ajax_posts() {

	$tax_query = ['relation' => 'AND'];

	foreach ($_POST['filters'] as $key => $value) {
	    $tax_query[] = [
	        'field' => 'term_id',
	        'taxononomy' => $key,
	        'terms' => [$value]
	    ];
	}

    // Query Arguments
    $args = array(
      'post_type' => 'the-talent',
      //'tax_query' => $tax_query,
      'tax_query' => array(
          'relation' => 'AND',
          array(
              'taxonomy' => 'level',
              'field'    => 'term_id',
              'terms'    => array( '25' ),// needs to be 3 and up? maybe use if statements?
          ),
          array(
              'taxonomy' => 'location',
              'field'    => 'term_id',
              'terms'    => array( '20' ),
          ),
          array(
              'taxonomy' => 'specialty',
              'field'    => 'term_id',
              'terms'    => array( '4' ),
          ),
          
      ),
    );

    var_dump($arg);
    print_r($arg);
    

    // The Query
    $ajaxposts = new WP_Query( $args );

    $response = '';

    // The Query
    if ( $ajaxposts->have_posts() ) {
        while ( $ajaxposts->have_posts() ) {
            $ajaxposts->the_post();
            //$response .= get_template_part('products');

            $response .= "";

            $name = get_field('name');
            $main_image = get_field('main_image');

         ?>

        

       

Cuối cùng, nó hoạt động với các truy vấn cho từng tình huống tùy thuộc vào bộ lọc nào trong số 3 bộ lọc (cấp độ, vị trí và/hoặc chuyên môn) được chọn. Tò mò không biết có cách nào tốt hơn việc có 7 câu lệnh if/else không?

Làm cách nào để chuyển Mảng JavaScript sang PHP?

Bạn có thể sử dụng JSON. stringify(array) để mã hóa mảng của bạn bằng JavaScript, sau đó sử dụng $array=json_decode($_POST['jsondata']); . .

Tôi có thể chuyển mảng trong AJAX không?

Lưu ý – Bạn có thể chuyển biến Mảng JavaScript giống như bất kỳ biến nào khác trong yêu cầu AJAX .

Hàm thành công AJAX là gì?

Thành công AJAX là gì? . Các sự kiện toàn cầu được kích hoạt trên tài liệu để gọi bất kỳ trình xử lý nào có thể đang nghe. Sự kiện ajaxSuccess chỉ được gọi nếu yêu cầu thành công. Về cơ bản, đó là một hàm loại được gọi khi yêu cầu được thực hiện .

Kiểu dữ liệu trong AJAX jquery là gì?

Các loại dữ liệu có sẵn là văn bản , html , xml , json , jsonp và tập lệnh . Nếu văn bản hoặc html được chỉ định, thì không có quá trình tiền xử lý nào xảy ra. Dữ liệu đơn giản được chuyển đến trình xử lý thành công và được cung cấp thông qua thuộc tính responseText của đối tượng jqXHR.