如何为jquery自动完成制作json代码? [关闭]
I need an json for jquery catcomplete and I would like you to help me...
I have this code
$( ".autocomplete" ).autocomplete({
source: "files/news.php?listar=json"
});
And I would like "files/news.php?listar=json" to display something like this:
[
{ label: "title1", category: "category1" },
{ label: "title2", category: "category2" }
]
Could you please help me?
@edit:
I tried this, but it didn't work:
if ($_GET['listar'] == 'json')
{
echo '['."
";
$query = mysql_query("SELECT * FROM noticias WHERE deletada='0' ORDER BY id DESC");
$a = 0;
while ($noticia = mysql_fetch_array($query))
{
echo ' { label: "'.$noticia['titulo'].'", category: "'.ucwords(Categoria($noticia['categoria'])).'" }';
$a++;
if ($a < mysql_num_rows($query))
{
echo ",
";
}
}
echo "
".']';
exit;
}
我需要一个json用于 jquery catcomplete 我想帮助你... p>
我有这段代码 p>
$(“。autocomplete”)。selfocomplete({
source:“files / news.php?listar = json”
});
code> pre>
我想“files / news.php?listar = json”显示如下内容: p>
[
{label:“title1”,category:“category1”} ,
{标签:“标题2”,类别:“category2”}
]
code> pre>
您能帮助我吗? p>
@edit: p>
我尝试了这个,但它不起作用: p>
if($ _GET ['listar' ] =='json')
{
echo'['。“
”;
$ query = mysql_query(“SELECT * FROM noticias WHERE deletada ='0'ORDER BY ID DESC”);
$ a = 0;
while($ noticia = mysql_fetch_array($ query))
{
echo'{label:“'。$ noticia ['titulo']。'”,category:“'。。Copyright(Categoria($ noticia ['categoria']))。''}';
$ a ++;
if($ a&lt; mysql_num_rows($ query))
{
echo“,
”;
}
}
echo“
”。']';
exit;
}
code> pre>
div>
You don't need writing own json, because it's already function for json encode()
: http://php.net/manual/en/function.json-encode.php
if ($_GET['listar'] == 'json')
{
$query = mysql_query("SELECT * FROM noticias WHERE deletada='0' ORDER BY id DESC");
while ($noticia = mysql_fetch_array($query))
{
$results[] = array(
'label' => $noticia['titulo'],
'category' => $noticia['categoria']
);
}
}
$json = json_encode($results);
header('Content-type: application/json');
echo $json;
exit;
Question is bit confusing. You are expecting JSON in PHP. In PHP, you can use build in function json_encode to convert any array into JSON and return it as response.
Your tags suggest you need it in JS. In JS, try json2.js