Looking for some advice on whether my syntax is correct for this Prototype to jQuery conversion.
I have both frameworks loading at the same time and would like to convert all scripts to jQuery to reduce page load weight and speed.
Prototype
Looking to replicate this in jQuery:
if (snapshots.items.length < snapshots.total_entries) {
new Ajax.Request(snapshots.url, {
method: 'GET',
parameters: {
page: snapshots.current_page + 1,
per_page: snapshots.per_page
},
onSuccess: function(response) {
var start = snapshots.items.length;
snapshots.items = snapshots.items.concat(eval(response.responseText));
for (i = start; i < snapshots.items.length; i++) {
$('snapshots').appendChild(render_snapshot(snapshots.items[i].snapshot));
Photo.Carousels.instances[Photo.Filmstrip.carouselIndex].slides.push($('slide_' + snapshots.items[i].snapshot.id));
Photo.Carousels.instances[Photo.Filmstrip.carouselIndex].slides[i]._index = i;
}
snapshots.current_page++;
Photo.Filmstrip.currentSnapshot(currentSnapshot);
}
});
}
to jQuery
if (snapshots.items.length < snapshots.total_entries) {
$j.ajax({
url: snapshots.url,
data: {
page: snapshots.current_page + 1,
per_page: snapshots.per_page
},
success: function (response) {
var start = snapshots.items.length;
snapshots.items = snapshots.items.concat(eval(response.responseText));
for (i = start; i < snapshots.items.length; i++) {
$j('.snapshots').append(render_snapshot(snapshots.items[i].snapshot));
Photo.Carousels.instances[Photo.Filmstrip.carouselIndex].slides.push($j('slide_' + snapshots.items[i].snapshot.id));
Photo.Carousels.instances[Photo.Filmstrip.carouselIndex].slides[i]._index = i;
}
snapshots.current_page++;
Photo.Filmstrip.currentSnapshot(currentSnapshot);
}
});
}
Yes, this looks right – I know jQuery much better than Prototype, so I’m guessing a little, but it makes sense (assuming you’ve used
$.noConflictto assignjQueryto$j). The only issue here, as @Greg pointed out in his comment, is theeval– I assume you’re returning JSON data, so if you include the config option:jQuery will parse this automatically, in a way that’s safer than a plain
eval. In fact, I’m pretty sure that in most cases if you leave this option out, jQuery will sniff your response body and guess intelligently whether to parse it as JSON, XML, HTML, script, or text, in which case yourevalwould be unnecessary.