Reputation: 535
I have two json files in which I have all news headlines and content for particular topic for that news (don't ask me why), so what I am trying to do is to load url with all headlines and after search by id for the right content.
It is looking like that:
$.ajax({
url: 'http://website.com/news.json?=list',
dataType: 'json',
success: function (data) {
$.each(data.news, function (newsId, newsHeadline) {
$('h1').after('<h2 id="question-' + newsId + '">' + newsHeadline + '</h2>');
$.get('http://website.com/news.json?=list&id=' + newsId, function (data) {
$('h2').after('<div class="accordion-content">' + data.result.newscontent + '</div>');
});
});
}
});
So far its working almost as expected, its is loading headlines and after loading content.
Problem is that it is loading all contents for each of headlines. For example by first url there is 2 headlines.
So it should be:
Headline 1
Content 1
Headline 2
Content 2
But instead it giving me:
Headline 1
Content 1
Content 2
Headline 2
Content 1
Content 2
Upvotes: 1
Views: 94
Reputation: 3233
I think it might have something to do with the use of the data variable twice. Try this:
$.ajax({
url: 'http://website.com/news.json?=list',
dataType: 'json',
success: function (data) {
$.each(data.news, function (newsId, newsHeadline) {
$('h1').after('<h2 id="question-' + newsId + '">' + newsHeadline + '</h2>');
$.get('http://website.com/news.json?=list&id=' + newsId, function (data2) {
$('h2').after('<div class="accordion-content">' + data2.result.newscontent + '</div>');
});
});
}
});
Edit:
Oops... looks like Pointy is correct. The $('h2') selector inside the $.get() function is getting ALL the h2 HTML elements on the page.
Upvotes: 0
Reputation: 25280
it's because of the async way ajax call works.
in the first loop you do ajax call with callback and continue to the second loop call (without waiting for the ajax to complete).
the ajax callback can be during another loop so instead of getting 1-1,2-2.3-3 you'll get 1-2,2-2,3-2,4-3 ...
if you need it to remain the same you should think on doing it on a linear way instead of nested async callbacks.
Upvotes: 0
Reputation: 414086
You're not qualifying the reference to <h2>
when you append in the $.get()
handler. Thus, the content is appended to all <h2>
elements.
Upvotes: 2