How do I get the JSON content from a JSON string in JQuery?
My JSON string(this is what i get after making the request in $.post )-
{"email":"bill gates"}
{"email":"steve jobs"}
{"email":"mark zuckerberg"}
{"email":"cristiano ronaldo"}
{"email":"wayne rooney"}
The code I am using to get the content-
$(document).ready(function() {
var data = new Object();
data.email = "yash.mathur13@gmail.com";
var dataString = $.toJSON(data);
$.post('templates/chat.php', {
data: dataString
开发者_运维技巧 }, function(json) {
$("body").append(json);
});
});
I want to dislay each one of them in an <li>
tag.
Try something like that:
var list = "<ul></ul>";
$.each(json, function(idx, value) {
list.append("<li>" + value.email + "</li>");
});
$("body").append("list");
take a look at http://api.jquery.com/jQuery.parseJSON/
should be able to do
var obj = $.parseJSON(json);
$.each(obj, function(index, item){
// append to your <ul> if it already exists, or build one up
$('ul').append('<li>' + item.email + '</li>');
});
You don't need to manually encode things to JSON with jQuery, usually.
Does the following Javascript work instead?
$(document).ready(function() {
var data = new Object();
data.email = "yash.mathur13@gmail.com";
$.post('templates/chat.php', data, function(response) {
$("body").append('<ul>' + response.map(function(elm) {
return '<li>' + elm + '</li>';
}).join('') + '</ul>');
});
});
精彩评论