I want to retrieve HTML and Javascript from the same page using AJAX calls. However, I'm not sure what the best, cleanest, and safest way to do this is. I want my Javascript to edit an already defined object on the client. So far, my idea is:
Client-side script executed on some event:
getMoreStuff = function () {
$.ajax({
url: '/someRoute',
success: function (data) {
$data = $(data);
$things = $data.find('#things');
$('#content').append($things);
// Execute the script
}
})
}
Body of AJAX request:
<div id="things">
<div class="post">...</div>
<div class="post">...</div>
<div class="post">...</div>
<div class="post">...</div>
<div class="post">...</div>
</div>
<script>
(function() {
window.things || (window.things = []);
things.concat([...some array...]);
})();
</script>
I'm not sure if my jQuery code executes it when I define $data
. Or should I send the script as a string and use eval?
Would this work?
$(document.body).append($data.find('script'));
See dataType here
"html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.