Json编码的PHP数组附加了null - javascript

在调试的这一点上,这就是我要发送给我的javascript的内容

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

这是我的ajax电话

  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);
  })

每次都会出错,在数据中我对空数组的响应字符串是

“[]空值”

整个函数都被引用以引用相同的东西,但我得到一个错误,并且在json的末尾附加了“ null”。

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());
}

参考方案

从您的php页面返回一些内容,之后添加die()以删除null

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

Javascript和Python JSON-未定义变量 - javascript

例如,如果您具有以下JSON对象(删除python的分号):values = { a: 1, b: { c: 2, d: { e: 3 } }, f: 4, g: 5 }; 如果您尝试在JS中打印values,它将正常工作。但是在Python中,它将返回错误NameError: name 'a' is not defined,这意味着未定…

PHP json_encode数组到javascript关联数组 - javascript

我有一些从PHP中读取的mysqli列。它正在完美地获取和回显。$results = mysqli_fetch_assoc(mysqli_query($conn, $querystring)); echo json_encode($results); //$results = {"title":"Sea Shells"…

如何在JQuery中操作JSONArray - javascript

我有一个php函数,它以JSON返回此代码{"0":{"title":"Dans l\u2019appartement"},"1":{"title":"A l\u2019a\u00e9roport - D\u00e9part de B\u00e9at…

编码JSON数据以保留json格式 - javascript

由于JSON值是动态生成的,并且其中的值是基于用户输入的,因此,如果用户在字符串中输入了不可接受的字符(如"),则会使json无效。就像是:{ "tag" : "demo", "value": "user " input" } 有没有一种方法可以编码或转义JS…

在提交时在表单操作中获取变量丢失 - javascript

            当表单由onchange事件提交时,它不会保留get变量view。任何想法为什么会发生这种情况?提交后,这是它进入的网址,index?month=February&year=2014<form action="index?view=list" class="pure-form pure-fo…