0

我正在使用 jquery autosuggest,并希望在所有项目出现之前添加一个默认标题。例如,当用户开始搜索时,第一个下拉项目会说“我们建议:”,然后是项目列表。这是我目前拥有的

 $term=$_GET["term"];

$query=mysql_query("SELECT DISTINCT regionFROM business where regionlike '$term%' limit 10"); $json=数组();

while($region=mysql_fetch_array($query)){
$json[]=array(
                'value'=> $region["region"],
                'label'=>$region["region"]
                    );
}

回声 json_encode($json);

我对 php 和 jquery 有一个合理的理解,但不是 json

谢谢你的帮助

4

1 回答 1

0

新答案:我之前可能误读了你的问题。也许你只是在问这个:

$( "#mylist" ).autocomplete({
  source: myjsonarray,
  open: function( event, ui ) {
    $('.ui-autocomplete').find('li:first').prepend("<div>We Suggest:</div>")
      }
});

访问“打开”事件,在第一个列表项之前添加一个 div。

旧答案:

//make an empty container
$myresults=array();

//manually create your first item
$myfirstitem=array("value"=>"We suggest","label"=>"We suggest")

//put your first item in the container
array_push($myresults,$myfirstitem);

// fetch your data
while $result=mysql_query("SELECT phrase from mytable"){

    //put each item in the container
    array_push($myresults,array(
        "value"=>$result,
        "label"=>$result
        ));
}

//$myresults is now full of phrases. 
///Uncomment this to check it if you want.
//var_dump($myresults);

//encode and echo your result
echo json_encode($myresults);

上面的代码说明了一种方法来做你想做的事。话虽如此,我可能不会将“我们建议”作为实际选项......如果您要展示棒球卡列表,那么用户选择“我们建议”作为他们的最爱是没有意义的棒球卡...

另外,不要让 json 打扰你——它只是一个“符号”。这个例子非常简单——想一想并将它用作任何其他数组。

您也可以更有效地执行此操作 - 您不需要返回标签和值......但这是另一个对话。

此外,不要使用 mysql_* 函数,这一点很重要。查看mysqli和pdo。

祝你好运,希望对你有所帮助。

于 2013-10-26T23:10:57.203 回答