为什么php数组不能转换为JSON?

时间:2015-03-06 21:38:31

标签: php arrays json

我正在从mysql数据库中读取数据,我将它们保存到一个如下所示的数组中:

Array
(
    [0] => aargau
    [1] => appenzell_au
    [2] => appenzell_in
    [3] => basel-land
    [4] => basel-stadt
    [5] => bern
    [6] => freiburg
    [7] => genf
    [8] => glarus
    [9] => graub�nden
    [10] => jura
    [11] => luzern
    [12] => neuenburg
    [13] => nidwalden
    [14] => obwalden
    [15] => obwalden
    [16] => schwyz
    [17] => solothurn
    [18] => st_gallen
    [19] => tessin
    [20] => thurgau
    [21] => uri
    [22] => waadt
    [23] => wallis
    [24] => zug
    [25] => z�rich
)

代码(client.class.php)这看起来像这样:

public function getCantons($country){
        $cantonsArray= array();
    //  $tmpArray = array();
        $sql_get_cantons = sprintf("SELECT name FROM locations WHERE country='".$country."'");
        $result = $this->CONNECTION->query($sql_get_cantons);
        while($row = mysqli_fetch_array($result)){  
            array_push($cantonsArray,$row['name']);
        }
        return $cantonsArray;
    }

我有其他PHP文件(server.php),它返回ajax调用的答案

if($_POST['command']=='cantons'){
        $country = $_POST['country'];
        $client = new Client();
       // $results = $client->getActiveItemsOfCategory('technology');
        $results = $client->getCantons($country);
        $jsonResults = json_encode($results);
        print_r($jsonResults);
    }

在AJAX CALL中(由于我使用与其他AJAX调用相同的代码,因此工作正常)我只是这样做:

 var jqxhr = $.post( "php/server.php", {country:COUNTRY,command:'cantons'},function() {

})
  .done(function(data) {
        console.log(data);
   })
  .fail(function(data) {
     alert(JSON.stringify(data));
  })
  .always(function() {

});

结果是空的

3 个答案:

答案 0 :(得分:0)

尝试将此添加到您的server.php

header('Content-Type: application/json');
echo $jsonResults;

答案 1 :(得分:0)

使用echo代替print_r输出您的JSON字符串

答案 2 :(得分:0)

问题在于字母的编码。显然,我使用的是德语字母,这就是造成这个错误的原因。