Im having trouble formatting my json array in jquery and I cant seem to find a suitable answer.
I have a mysql database of users that is outputting thier user id and name in json format.
$result = mysql_query("SELECT id,info FROM users WHERE info like '$keyword%'");
while($row=mysql_fetch_assoc($result))
$return[] = $row;
echo json_encode($return);
Resulting in this output:
[{"id":"1","info":"Mike"},{"id":"2","info":"Sally"},{"id":"3","info":"Ben"}]
my jquery success looks like this:
$.each(data, function()
{
$.each(this, function(k, v)
{
$('.results').append('<li id='+k+'>'+v+'</li>');
});
});
resulting in this output:
<li id='id'>开发者_StackOverflow社区1</li>
<li id='info'>Mike</li>
<li id='id'>2</li>
<li id='info'>Sally</li>
etc...
But I would like it to read:
<li id='1'>Mike</li>
<li id='2'>Sally</li>
<li id='3'>Ben</li>
Ive been trying to wrap my brain around how to get this working but cant come up with anything, does anyone have any suggestions?
Try:
$.each(data, function() {
$('.results').append('<li id="' + this.id + '">' + this.info + '</li>');
});
However, DOM manipulation is slow, and whilst this won't be noticable for a small number of results, if you're adding a lot of <li>
's at the same time, you'll find the following code more efficient:
var str = '';
$.each(data, function() {
str += '<li id="' + this.id + '">' + this.info + '</li>';
});
$('.results').append(str);
Much easier than you thought, eh? :)
Edit: A brief description of why this works, and yours didn't:
What you've got is an array of objects. When you call $.each over data
, it iterates through the array. Inside the callback function you pass to each
, this
is equal to the current element in the array; which is the object. So we access the id
and the info
attributes of the object (this.id
and this.info
), and build a <li>
out of it.
Try removing the inner $.each
and doing:
$.each(data, function()
{
$('.results').append('<li id='+this.id+'>'+this.info+'</li>');
});
Consider, an associative array from PHP is an object for JavaScript. Additionally, your JSON is absurd over sized. (indexed index)
var name=["Mike","Sally","Ben"];
for(var i=0;i<name.length;i++){//Yes, it has a length.
$('.results').append('<li id='+i+'>'+name[i]+'</li>');
}
would be enough. If you insist on your solution - you forgot some brackets.
[[{"id":"1","info":"Mike"}],[{"id":"2","info":"Sally"}],[{"id":"3","info":"Ben"}]]
精彩评论