Reputation: 93
trying to loop to get my datas:
$.ajax({
type: 'POST',
url: '',
dataType: 'json',
data: {
Id: id
},
success: function (data) {
var detaildata = '';
var obj = data;
for (var m in obj)
{
detaildata = detaildata + obj[m];
}
},
error: function (ex) {
var r = "There is a problem";
alert("Message: " + r);
}
});
Output: [object Object][object Object][object Object][object Object]
At least, number of object is correct (4).
My object is coming from a linq query:
var queryList = (from media in _context.Medias
where media.ProductId == Id
orderby media.MediaOrder
select new
{
MediaName = "<div><img src='https://www.example.com/img/" + media.MediaName + "' class='img - thumbnail' style='width: 150px' /></div>"
}).ToList();
If I take it as .FirstOrDefault() and don't loop, output is perfect!
Upvotes: 0
Views: 87
Reputation: 93
Finally got it work simply with:
detaildata = "<div class='row'>";
for (var m in data)
{
detaildata = detaildata + data[m]['MediaName'];
}
detaildata = detaildata + "</div>";
Thanks @HymnZzy for your help.
Upvotes: 0
Reputation: 2925
Your loop logic is not complete. As per the linq query, the output is an array of JSON objects with property MediaName
. You'll need specify the property to extract the links. Try this.
$.ajax({
type: 'POST',
url: '',
dataType: 'json',
data: {
Id: id
},
success: function (data) {
var detaildata = data.map((obj)=>{ return obj['MediaName'] }); // for array
},
error: function (ex) {
var r = "There is a problem";
alert("Message: " + r);
}
});
use var detaildata = data.reduce((str,obj)=>{ return str+obj['MediaName'] });
if you want the output in a string
Upvotes: 0
Reputation: 422
Assuming your JSON is like this:
var data= {
"datas": [
{ "FirstName":"John" , "LastName":"Doe" },
{ "FirstName":"Anna" , "LastName":"Smith" },
{ "FirstName":"Peter" , "LastName":"Jones" }
]
}
Then you can query like this:
$.each(data.datas, function(index,data) {
alert(data.FirstName+" "+data.LastName)
});
sample:
http://jsfiddle.net/4HxSr/9/
Upvotes: 1