php返回空的JSON数组

时间:2016-04-30 08:18:21

标签: javascript php json

我创建了一个城镇名称阵列,"奥克兰"和"汉密尔顿",但是来自php的回复总是空的,任何想法?

更新: 经过调试,我发现问题出在php查询中 "城镇=' $ town' ",一旦我删除了这一行,其余的就完美了。 但我仍然无法弄清楚原因:<

javascript:

 var _addNewTowntoList = function(){
     if (_request.readyState == 4) {
            if (_request.status == 200) {
                var data = JSON.parse(_request.responseText);
                if(data.length == 0){
                    alert("No such town");
                    return;
                }

                 var t = data[0].town;
                 var o = data[0].outlook;
                 var min = data[0].min_temp;
                 var max = data[0].max_temp;    

                 var witem = new WLine(t,o,min,max);
                 console.log(t+" "+o+" "+min+" "+max);
                 _list.push(witem);
             }
         }
 }

这是php

   $town = $POST_['town'];
   $query = "Select * From weather WHERE town = '$town'";
   $result = mysqli_query($conn, $query);
   //create array for data
   $data = array();
   while($row = mysqli_fetch_assoc($result))
   {

        $data[] = $row;
   }
   echo json_encode($data);

2 个答案:

答案 0 :(得分:0)

更改此

graph G 
{
    { rank=same;  a;  b; }
    a [ shape = point ];
    b [ shape = point ];
    a -- b [ label = "e" ];
\\  add this
    c [ style = invis ];
}

$town = $POST_['town'];

>  $query = "Select * From weather WHERE town = '$town'";

答案 1 :(得分:0)

请记住properly escape查询字符串

$town = mysqli_real_escape_strin($conn, $_POST['town']);

因为您的脚本打开了SQL Injection攻击

除了$_POST的正确名称之外,这里要提到的另一件事是你可以使用mysqli_fetch_all函数一次获取所有结果并避免循环。例如

echo json_encode(mysqli_fetch_all($result, MYSQLI_ASSOC));