質問

I am using jquery autosuggest and would like to add a default heading just before all the items appear. For example when the user starts his search the first drop down item would say 'We Suggest:' followed by the list of items. Here is what I currently have

 $term=$_GET["term"];

$query=mysql_query("SELECT DISTINCT region FROM business where region like '$term%' limit 10 "); $json=array();

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

echo json_encode($json);

I have a reasonable understanding of php and jquery but not json

Thanks for any help

役に立ちましたか?

解決

NEW ANSWER: I may have misread your question before. Perhaps you are just asking for this:

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

Access the "open" event, add a div before the first list item.

OLD ANSWER:

//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);

The above code illustrates one way to do what you want to do. With that said, I'd probably not put "We Suggest" as an actual option... if you're presenting a list of baseball cards, it wouldn't make sense for the user to choose "we suggest" as their favorite baseball card...

Also, don't let json bother you- it's just a "notation". This example is very simple- think of it and use it as any other array.

You can also do this more efficiently- you don't need to return a label and a value... but that's another conversation.

Also, it's important that you do not use mysql_* functions. Look into mysqli and pdo.

Good luck, I hope that helped.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top