According to this answer, it is better to use the $.ajax() function:
$('.showprayer').click( function(event) {
$.ajax({
url: '/show_prayer',
type: 'POST',
data { 'name' : $(this).text() },
dataType: 'script'
});
});
rather than the $.post() function:
$('.showprayer').click( function(event) {
$.post('/show_prayer', { 'name' : $(this).text() }, function(data) {
eval(data);
});
});
The reason given is:
The difference is that this uses `jQuery.globalEval()` which sticks the script
in the <head> as if it were a normal GET requested <script>, instead of actually
calling `eval()` on it.
My question is, if this is correct, why is it important for the script to end up in the ? Does that make a big difference over using eval()?
The difference in your examples has nothing to do really between .post() and .ajax(), it’s just about built-in JS eval() vs. jQuery.globalEval(). These differences are covered here:
http://api.jquery.com/jQuery.globalEval/
but they don’t do a great job of explaining why it matters. Here’s the issue: if you do just do an ordinary eval of a line like:
from inside a .post() call, that “foo” variable will only live inside that call. If you later do anything else on that page, that variable will be gone, because it was scoped to the anonymous that you passed in to your “post”. In contrast, the jQuery “globalEval” method will make that foo variable a property of window, ie. it will be in the global scope. This means that any other function you subsequently run will still have access to it.
(Side Note: Putting lots of variables in the global scope isn’t actually always a good idea, because of potential naming conflicts, so the globalEval isn’t always better.)
In any case, you don’t have to stop using post to get the benefits of your returned script’s variables being global. Just do:
in your post function instead of “eval” and you’ll be all set.