我正在调用一个函数,我希望得到一些价值.但我没有任何价值.
我该如何使用返回值?
$(function () {
$(".datepicker").datepicker({
beforeShowDay: function (date) {
var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [array.indexOf(string) == -1]
console.log(array.indexOf(string) == -1);
}
});
});
var BDate = gateDateBooking(); // Calliing a function
var BookingDate = Bdate; // But i did't get any responce here
function gateDateBooking(){
$.ajax({
url: "localhost/CodeIgniter_2.2.0/index.php/admin/GetBookingDate",
type: "POST",
dataType: "text",
cache: false,
success: function (data) {
alert(data);
return data; // return responce
}
});
}
Run Code Online (Sandbox Code Playgroud)
您不能从异步回调中间返回值.它会将值返回给success调用者(在ajax代码中).
虽然看起来"工作",但你永远不应该考虑使用ajax async: false选项
相反,你可以使用传递给gateDateBooking函数的回调,或者使用jQuery promises(或者只是将代码放在success回调中 - 但这不灵活):
回调版本如下所示:
gateDateBooking(function(data){
var BookingDate = data; // Do something with the data when it is ready
});
function gateDateBooking(cb){
$.ajax({
url: "localhost/CodeIgniter_2.2.0/index.php/admin/GetBookingDate",
type: "POST",
dataType: "text",
cache: false,
success: function(data){
// call the callback passed
cb(data);
}
});
}
Run Code Online (Sandbox Code Playgroud)
这是使用$.ajax返回的Ajax承诺的示例.
gateDateBooking().done(function(data){
var BookingDate = data; // Do something with the data when it is ready
});
function gateDateBooking(){
// return the ajax promise
return $.ajax({
url: "localhost/CodeIgniter_2.2.0/index.php/admin/GetBookingDate",
type: "POST",
dataType: "text",
cache: false
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8457 次 |
| 最近记录: |