If I want to separate out my ajax success
function so that it is defined elsewhere in my <script>
, does it have to be inside the
$(document).ready(function()
{
section or could it be defined along with non-jQuery javascript functions?
$.ajax(
{
url: '/load_prayer',
cache: false,
dataType: 'json',
type: 'POST',
data: ({ 'prayerId' : prayerId }),
success: function(data)
{
$('#prayer_date').html(data.Date);
console.log(data);
},
error: function(e, xhr)
{
console.log(e);
}
});
The reason I don't want to define it inside the call to ajax
is it will eventually be a large function and it will be confusing to read if it's mixed in with the other ajax
call parameters.
For example, would this work:
$.ajax(
{
url: '/load_prayer',
cache: false,
dataType: 'json',
type: 'POST',
data: ({ 'prayerId' : prayerId }),
success: handlePrayer(data),
error: function(e, xhr)
{开发者_JS百科
console.log(e);
}
});
handlePrayer(data)
{
$('#prayer_date').html(data.Date);
console.log(data);
}
You have to change it so its only the function name. Like so:
$.ajax(
{
url: '/load_prayer',
cache: false,
dataType: 'json',
type: 'POST',
data: ({ 'prayerId' : prayerId }),
success: handlePrayer,
error: function(e, xhr)
{
console.log(e);
}
});
And you need put function where you declare it like so
function handlePrayer(data)
{
$('#prayer_date').html(data.Date);
console.log(data);
}
As long as the function has been loaded before $.ajax is called, it should work. That means it can be outside $(document).ready(...)
.
With one exception: All variables that need to be accessed need to be outside that success function. The below ajaxCallWorked()
function would be able to access outside
but not inside
.
var outside;
function ajaxCallWorked(data) {
...
}
$(document).ready(function() {
var inside;
$.ajax({
...
success: ajaxCallWorked,
...
});
}
i believe you can define the function outside the scope of both the ajax call and the onready.
精彩评论