简体   繁体   English

以JSON格式返回Mysql SQL结果

[英]Returns Mysql SQL results in JSON format

I am trying to implement Typeahead.js to my site. 我正在尝试将Typeahead.js实施到我的网站。

The typeahead.js will take from a remote page that would return JSON, typeahead.js将取自返回JSON的远程页面,
something like: http://example.org/search?q=%QUERY 类似于: http://example.org/search?q=%QUERY : http://example.org/search?q=%QUERY

For my site, this is what I've wrote for the PHP: 对于我的网站,这是我为PHP编写的内容:

$q=mysql_real_escape_string($_GET['q']);

$getship= @mysql_query('SELECT * FROM `tbl` WHERE data1 LIKE \'%'.$q.'%\' OR schar LIKE \'%'.$q.'%\';');

while($tbl=mysql_fetch_array($getship)){
    $id=$tbl['id'];
    $data1=$tbl['data1'];
    $fplod=explode(" ",$data1);
    $data2=$tbl['data2'];
    $splod=explode(" ",$data2);
    $data3=$tbl['data3'];
    $data4=$tbl['data4'];
    echo '{
            "value":'.$id.',
            "tokens":["'.$fplod[0].'","'.$fplod[1].'","'.$splod[0].'","'.$splod[1].'"],
            "data1" :"'.$data1.'",
            "data2":"'.$data2.'",
            "data3":"'.$data3.'",
            "data4":"'.$data4.'"
        }';
}

But when ever I ask that typeahead thing to return, it seems to return in text/html and not application/json 但是,无论何时我要求提前输入要返回的内容,它似乎都以text / html而不是application / json返回 Chrome浏览器中的屏幕截图 .

How can I make this to work? 我该如何运作?

Thanks in advance 提前致谢

You can set the Content-Type header yourself. 您可以自己设置Content-Type标头。 Before any output is sent, call header : 在发送任何输出之前,请调用header

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

That is not valid JSON. 那是无效的JSON。 You do not have quotes around the names. 您在名称两边没有引号。 PHP has built in json encoding/decoding functions already so you don't have to build the string yourself. PHP已经内置了json编码/解码功能,因此您不必自己构建字符串。

echo json_encode(array("value" => $id /* etc

It is not a good practice to convert your data into json manually, rather use json_encode 手动将数据转换为json并不是一个好习惯,而是使用json_encode

$data = array();
while($tbl=mysql_fetch_array($getship)){
   $data[] = $tbl;
}
$return = array("data"=>$data);
echo json_encode($return);

try something like: 尝试类似:

while($row = mysql_fetch_array($getship, MYSQL_ASSOC))
{
    $row_set[] = $row;
}

echo json_encode($row_set);

you can also use mysql_fetch_assoc. 您也可以使用mysql_fetch_assoc。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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