Reputation: 1162
In the question asked here, i see that the following code can be used for adding options to SELECT
function getResults(str) {
$.ajax({
url:'suggest.html',
type:'POST',
data: 'q=' + str,
dataType: 'json',
success: function( json ) {
$.each(json, function(i, optionHtml){
$('#myselect').append(optionHtml);
});
}
});
};
Can someone please tell me, what the format of the json should be, on the php server side. Like, how should it be created, so that it is parsed correctly by "$('#myselect').append(optionHtml);" ??
Upvotes: 0
Views: 684
Reputation: 119877
That code would parse this JSON, basically an array of strings with markup.
[
"<option value='...</option>",
"<option value='...</option>",
"<option value='...</option>",
...
]
This pretty much defeats the purpose of JSON though.
It would have been better if the JSON contained only the data:
{
"text1" : "value1",
"text2" : "value2",
"text3" : "value3",
...
}
and your code to parse it and create the elements for you. That way, the JSON is lighter.
success: function( json ) {
var mySelect = $('#myselect')
$.each(json, function(key,val){
$('<option/>',{
value : val //i like this method of making elements better
}) //because string concatenation is messy
.text(key)
.appendTo(mySelect);
});
}
Upvotes: 4
Reputation: 10619
JSON is a collection of key value/name pairs. These can be in the form of Objects or Arrays or both.
Let me assume that you want to have two dropdowns and First dropdown has Countries and the second one has the cities of that particular country in it. In this case the JSON structure would be like the below:
{
"<select value='usa'>USA</select>": "<option value='boston'>Boston</option>",
"<select>FRANCE</select>": "<option value=paris'>Paris</option>",
"<select>UNITED KINGDOM</select>": "<option value=london'>London<option value=not'>Nottingham</option>",
"<select>GERMANY</select>": "<option value='munich'>Munich</option>"
}
JSON Validated at http://jsonlint.com/
Upvotes: 0
Reputation: 150070
To use with the JS you've shown you'd need the JSON to be an array like this:
["<option value='Woodland Hills'>Woodland Hills<\/option>","<option value='none'>none<\/option>","<option value='Los Angeles'>Los Angeles<\/option>","<option value='Laguna Hills'>Laguna Hills<\/option>"]
...where each array element is the appropriate html for a single <option>
element.
(That is, exactly like the first JSON shown in that other question.)
Upvotes: 0