Cách gửi dữ liệu mảng bằng ajax trong php?

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ử cách đó 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);

Cách gửi dữ liệu mảng bằng ajax trong php?
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?

Chúng tôi có thể gửi Mảng qua AJAX không?

từng hàm(). Truyền các biến đã khởi tạo dưới dạng dữ liệu trong yêu cầu AJAX. Ở đây, tên và email là biến kiểu chuỗi và lang là biến Mả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 .

Làm cách nào để gửi và nhận dữ liệu bằng AJAX?

Gửi yêu cầu POST http bằng cách sử dụng ajax() .
$. Phương thức ajax() cho phép bạn gửi các yêu cầu http không đồng bộ để gửi hoặc truy xuất dữ liệu từ máy chủ mà không cần tải lại toàn bộ trang
$. ajax() có thể được sử dụng để gửi http GET, POST, PUT, DELETE, v.v. .
cú pháp. $. .
Sử dụng tham số tùy chọn để tùy chỉnh yêu cầu ajax theo nhu cầu của bạn

Mảng trong AJAX là gì?

Mảng được dùng để lưu trữ nhiều giá trị trong một biến duy nhất . Điều này có thể được sử dụng để chuyển nhóm các giá trị liên quan dưới dạng dữ liệu tới $. ajax để xử lý và nhận phản hồi. e. g. vượt qua tất cả các giá trị hộp kiểm đã chọn, các giá trị được chọn từ danh sách. 08-May-2022.

Bạn có thể sử dụng AJAX với PHP không?

Bắt đầu sử dụng AJAX ngay hôm nay . Tập lệnh máy chủ sẽ được viết bằng PHP . Nếu bạn muốn tìm hiểu thêm về AJAX, hãy truy cập hướng dẫn AJAX của chúng tôi.