jquery datepicker pass variable from one function to another
i'm trying to pass the data i got from the function initiated by onChangeMonthYear to the function initiated by beforeShowDay. I tried various methods, like assigning the data I got from test.php to a variable declared at the outside but to no avail. so what i did was just update a text field with the retrieved data from test.php, and asks the function in beforeShowDay to get the data from there. here's a portion of my code
$(document).ready(function() {
$('#datepicker').datepicker({dateFormat: 'dd-mm-yy', currentText: 'Now', changeMonth: true, changeYear: true, altField: '#alternate', altFormat: 'DD, d MM, yy', onSelect: function(dateText, inst) {},
onChangeMonthYear: function(year,month,inst){
$.post("test.php", {action: "TEST", month: month, year: year},
fun开发者_如何学JAVAction (data){
$("#datafromphp").val(data);
}
,"html");
},
beforeShowDay: function (date){
var getdatafromphp= $("#datafromphp").val();
}
});
});
surely there's a better way to do this?
If I understand you correctly, you want to grab some data via AJAX asynchronously in onChangeMonthYear
and make it accessible in beforeShowDay
in order to display the updated data.
It helps to understand the order of the calls. When the calendar first appears, a bunch of calls are made to beforeShowDay
. At this stage, there is no data from your AJAX call yet (i.e. from test.php
).
Once the user changes the month/year, onChangeMonthYear
will be called, and a bunch of calls are then made to beforeShowDay
again. At this stage, there should still be no data from your AJAX call, unless the AJAX call to test.php
manages to return quickly enough for some of the calls to beforeShowDay
to access the returned value.
Then the AJAX call returns and the returned data is somehow passed to beforeShowDay
to display.
As you can see, what you tried to do would not work, as the AJAX call would not be on time for beforeShowDay
to grab the data even if you "pass" it correctly. What you want to do is, assign the returned data from AJAX somewhere, and then refresh the datepicker, so beforeShowDay
would be called again. You can store data to an arbitrary jQuery object with .data()
. So, you can do something like this:
$('#datepicker').data('datafromphp', []).datepicker({dateFormat: 'dd-mm-yy', currentText: 'Now', changeMonth: true, changeYear: true, altField: '#alternate', altFormat: 'DD, d MM, yy', onSelect: function(dateText, inst) {},
onChangeMonthYear: function(year,month,inst){
$.post("test.php", {action: "TEST", month: month, year: year},
function (data){
$("#datepicker").data('datafromphp', data).datepicker('refresh');
}
,"html");
},
beforeShowDay: function (date){
var getdatafromphp= $(this).data("datafromphp");
}
});
精彩评论