jquery 1.5.1 Deferred Object .when() .then() Confusion
I have two webmethods returning dates from a .net 3.5 page.
Each return a start and end date string, respectively. I try calling them and then outputting their results after they both complete as an alert as a simple test, yet I cannot do this successfully. When I step through my code, the alert is displayed before the global vars are filled. Once the alert is displayed, the vars are filled. What am I doing wrong?<script type="javascript">
var startDate, endDate;
$(document).ready(function(){
$.when(GetStartDate(), GetEndDate()).then(Output());
});
function GetStartDate(){
return $.ajax({
type="POST",
url="myurl/page.aspx/GetStartDate",
data = {},
contentType="json",
success: function(data){ startDate = data.d.toString();},
failure:failureAlertMsg
});
}
function GetEndDa开发者_开发问答te(){
return $.ajax({
type="POST",
url="myurl/page.aspx/GetEndDate",
data = {},
contentType="json",
success: function(data){ endDate = data.d.toString();},
failure:failureAlertMsg
});
}
function Output(){
alert('StartDate: ' + startDate + '\nEndDate: ' + endDate');
}
</script>
you're executing those functions GetStartDate, GetEndDate and Output immediately, i don't think this is what you want.
I'm not familiar with the new Deferred object feature, but my guess here is that you want to pass the reference to the function, which will then execute that function at the appropriate time. In your case, you're saying, execute this function immediately, hence your alert happens immediately, and you'll also see your ajax req's happening immediately, though you might not notice due to the async nature of ajax.
Something like
$.when(GetStartDate, GetEndDate).then(Output);
might be more appropriate?
additional info
If you read over the jquery docs for .then
, you'll see that it should provide a done
and failure
callback, since you're just giving one, I'd use done
instead:
$.when(GetStartDate, GetEndDate).done(Output);
Again I don't know exactly how deferred objects work, but I would start by using the console to log some messages. For instance in each success callback for your ajax functions do something like, console.log(">> GetStartDate:success()")
or something to that effect, so you can see if the success function is being called properly. Is it the case with deferred objects that the success
callback of your ajax function is still called? I couldn't find information on this, but it may be that it actually passes these values on to your done
callback function and you access everything there? Not entirely sure.
I figured it out thanks to this article: http://jsfiddle.net/ehynds/Mrqf8/
What I did is edit this:
$(document).ready(function(){
$.when(GetStartDate(), GetEndDate()).then(Output());
});
to this:
$(document).ready(function(){
$.when(GetStartDate(), GetEndDate())
.then(function(){
Output();
})
//additional option, not required
.fail(function(){
alert:'Failed!');
})
});
精彩评论