【问题标题】:Json with PHP mysql and JqueryJson 与 PHP mysql 和 Jquery
【发布时间】:2012-11-08 16:26:25
【问题描述】:

我有一个奇怪的问题..

当我尝试使用相应的数字 [0]、[1] 等访问我的 json 代码时。我只得到对象的第一个字符。

首先是我的代码:

test2.php

if(isset($_POST['getCustomersArray'])){
$runQuery = mysql_query($Query) or
        die("SQL: $Query)<br />".mysql_error()); 
$numrows = mysql_num_rows($runQuery); 
$array = array(array());

for($i = 0;$i <= 2; $i++){
    $row = mysql_fetch_array($runQuery);
    $array[$i]['namn'] = $row['fornamn'];

}
    print json_encode($array);
}

scriptfile.js

$.ajax({
    type:"POST",
    url: "test2.php",
    data: "getCustomersArray=true",
    datatype: "JSON",
    cache: false,
    success: function(json) {
            console.log(json[0]);
     }
});

结果(来自console.log(json[0])):

[

console.log(json) 的结果:

[{"namn":"the first name"},{"namn":"The secound name"},{"namn":"the third name"}]

我不确定为什么会有方括号,但也许应该有?

我已经对这个问题感到困惑一段时间了,我确信它有些愚蠢。请帮忙。

【问题讨论】:

    标签: php jquery mysql json


    【解决方案1】:

    您在 AJAX 设置中的选项不正确,

    datatype: "json",
    

    应该是:

    dataType: "json",
    

    【讨论】:

    • 试试小写的json。 dataType: "json"
    • @Martin Aha,我认为 jQuery 默认是小写的。
    • 老实说我也想过,但好像没有,哈哈!
    【解决方案2】:
    datatype: "JSON",
    

    应该是

    dataType: "json",  // json in lowercase and T has to be captalized
    

    【讨论】:

      【解决方案3】:

      确保您拥有以下代码:

      if(isset($_POST['getCustomersArray'])){
      $runQuery = mysql_query($Query) or
          die("SQL: $Query)<br />".mysql_error()); 
      $numrows = mysql_num_rows($runQuery); 
      $array = array(array());
      
      for($i = 0;$i <= 2; $i++){
          $row = mysql_fetch_array($runQuery);
          $array[$i]['namn'] = $row['fornamn'];
      }
      header("Content-Type: application/json; charset=UTF-8");
      print json_encode($array);
      }
      

      这里您需要将 content-type 设置为 application/json 并设置正确的字符集以避免任何跨浏览器问题。看看我网站上的以下教程,它应该涵盖所有这些内容,也许还可以对您的代码进行一些改进:PHP jQuery Search Tutorial - using JSON object the proper way

      希望这会有所帮助:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-31
        • 2011-09-27
        • 1970-01-01
        • 2012-07-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多