Moving data outside of the scope my jQuery AJAX call
I have a little AJAX function that asks the server whether a particular checkbox should be checked. I'd like to pass the information to a variable outside of the scope of the AJAX function. Something along the lines of:
isChecked = $.ajax({
type: "POST",
url: "/ajax/subscribe-query/",
data: "selfKey=" + commentData['selfKeyValue'],
success: function(isSubscribed){
if(isSubscribed == 'true'){
return = true;
}
else{
return = false;
}
}
开发者_运维技巧 })
or
var isChecked;
$.ajax({
type: "POST",
url: "/ajax/subscribe-query/",
data: "selfKey=" + commentData['selfKeyValue'],
success: function(isSubscribed){
if(isSubscribed == 'true'){
isChecked = true;
}
else{
isChecked = false;
}
}
})
Neither of those works of course. How do I do this?
var isChecked;
$.ajax({
type: "POST",
url: "/ajax/subscribe-query/",
data: "selfKey=" + commentData['selfKeyValue'],
success: function(isSubscribed){
if(isSubscribed == 'true'){
isChecked = true;
}
else{
isChecked = false;
}
}
});
alert('isChecked');
in this code even if the 'isChecked' property is set properly in the ajax success function the alert will say undefined
because the ajax call is Asynchronous
. It will raise the alert before the ajax success function returns. Therefore you need to do your work after the ajax success function like this. You can pass the variable to do the work after ajax success.
$.ajax({
type: "POST",
url: "/ajax/subscribe-query/",
data: "selfKey=" + commentData['selfKeyValue'],
success: function(isSubscribed){
chek(isChecked);//pass the variable here
}
});
function chek(isChecked){
if(isChecked){
$('#YourCheckbox').attr('checked','checked')
}
else{
$('#YourCheckbox').removeAttr('checked')
}
}
I'd recommend creating an object that has an isChecked property. That's safer than using a simple global variable. For example:
var inputObj = {};
$.ajax({
type: "POST",
url: "/ajax/subscribe-query/",
data: "selfKey=" + commentData['selfKeyValue'],
success: function(isSubscribed){
if(isSubscribed == 'true'){
inputObj.isChecked = true;
}
else{
inputObj.isChecked = false;
}
}
})
精彩评论