简体   繁体   中英

Json Encoded PHP array has null appended to it

At this point in the debugging this is what I am sending to my javascript

  header("Content-Type: application/json");
  //echo json_encode($full_product_list);
  echo json_encode(array());

and here is my ajax call

  jQuery.get( "non public api sorry ")
    .done(function(data) {
      console.log("I got a response")
      console.log(data)
    })
    .fail(function(data) {
      console.log("Error?")
      console.log(data);
  })

It errors everytime and in the data my response string for the empty array is

"[]null"

Entire function being called for reference same thing I get an error and at the end of my json there is "null" appended.

function getAllProducts() {
  $full_product_list = array();
  $loop = new WP_Query( array( 'post_type' => 'product', 'posts_per_page' => -1 ) );
  $pf = new WC_Product_Factory();

  while ( $loop->have_posts() ) : $loop->the_post();
    $post_id = get_the_ID();
    $product = $pf->get_product($post_id);
    $attributes = $product->get_attributes();
    $attrs = array();

    foreach ($attributes as $attr) {
      $name = str_replace("pa_fablab_", "", $attr["name"]);
      $attrs[$name] = $attr["value"];
    }

    $item = array(
      "id" => $post_id,
      "name" => get_the_title(),
      "price" => $product->get_price()
    );

    if (sizeof($attrs) > 0) {
      $full_product_list[] = array_merge($item, $attrs);
    }
  endwhile; wp_reset_query();
  header("Content-Type: application/json");
  //echo json_encode($full_product_list);
  echo json_encode(array());
}

Return something from your php page, add die() after to remove the null

header("Content-Type: application/json");
  //echo json_encode($full_product_list);
  echo json_encode(array("message"=>"ok"));
  die();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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