JSON or XML either way I need to format a JS array from a URL
I'm using the JQuery Aut开发者_JS百科ocomplete plugin and I need some help formatting data available to me. I have a url that can output data in XML or JSON:
JSON example:
[{"location":{"address":"Dortha Pike","city":"Emmerichburgh","created_at":"2011-05-19T00:03:20Z","id":3,"name":"Caroline Fahey DDS","state":"Illinois","updated_at":"2011-05-19T00:03:20Z","zip":"80822-2018"}}
XML example:
<locations type="array">
<location>
<address>Dortha Pike</address>
<city>Emmerichburgh</city>
<created-at type="datetime">2011-05-19T00:03:20Z</created-at>
<id type="integer">3</id>
<name>Caroline Fahey DDS</name>
<state>Illinois</state>
<updated-at type="datetime">2011-05-19T00:03:20Z</updated-at>
<zip>80822-2018</zip>
</location>
The function below accepts data in a JS array. My problem is I need to take either of the above data and format it like you see var data is below:
$(document).ready(function(){
var data = "Core Selectors Attributes Traversing Manipulation CSS Events Effects Ajax Utilities".split(" ");
$("#example").autocomplete(data);
});
If your using the autocomplete I think your using, the string seperated by spaces is only one format... you can use JSON as long as you have particular names for the variables.
$item = $item . "{ \"id\": \"$id\", \"label\": \"$name\"},";
So in your case you have to pick a field, like name, and parse all the names into a string like:
[
{
"id": 1,
"label": "Caroline Fahey DDS"
},
{
"id": "2",
"label": "Another Name"
}
]
Can certainly help you with that, just check that string works first as it might be a different plugin.
EDIT: Provided example
the php/ajax response
<?php
$q = getGET("term");
if($q != "")
{
$q = fquery_sanitize($q);
$sql = "select ManufacturerID, ManufacturerName from sds_manufacturer ".
" where ManufacturerName LIKE '%$q%' ".
" order by ManufacturerName";
$result = fquery_db($sql);
$item= "";
while($row=mysql_fetch_assoc($result))
{
$id = $row["ManufacturerID"];
$name = $row["ManufacturerName"];
$item = $item . "{ \"id\": \"$id\", \"label\": \"$name\"},";
}
echo "[";
echo trim($item, ",");
echo "]";
}
?>
The autocomplete
$('.manufacturer-form .name').autocomplete({
source: "/portal/inc/prod_manage/man-list-json.php",
minLength: 3,
select: function( event, ui ) {
manufacturer_select(ui.item.id);
}
精彩评论