[英]jQuery array doesn't work after Ajax call
我正在使用jquery.timepicker插件。 (鏈接: http : //jonthornton.github.io/jquery-timepicker/ )
請參考下面的代碼示例(有效)
var disableTime= [['12:30 PM', '1:00 PM'], ['11:30 AM', '12:00 PM']];
$("#InterviewTime").timepicker(
{
'minTime': '7:00am',
'maxTime': '9:00pm',
'disableTimeRanges': disableTime
}
);
但是,我需要通過Ajax調用從服務器獲取“ disableTime”變量的數據。 為此,我正在准備ac#字符串(在我的ASP.NET MVC控制器中),其格式與上面在“ disableTime”變量中顯示的格式相同。 我在jQuery中收到格式化的字符串作為Json字符串,然后將字符串轉換為javascript數組...如下所示
var disableTime = jQuery.makeArray(data);
但這不起作用
任何猜測為什么它不起作用?
如果我通過console.log(jQuery.makeArray(data))手動復制數據,然后將硬編碼的復制值分配給“ disableTime”變量,則它再次可以正常工作。
這是完整的代碼
var outputStr = "[['12:30 PM', '1:00 PM'], ['11:30 AM', '12:00 PM']]";
return Json(outputStr, JsonRequestBehavior.AllowGet);
$.ajax({
url: '@Url.Action("GetUnavailableTime", "Interview")',
type: 'GET',
data: { 'scheduledDate': scheduledDate, 'timeZone': timeZone},
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (data) {
var disableTime = jQuery.makeArray(data);
$("#InterviewTime").timepicker(
{
//'minTime': newtime,
'minTime': '7:00am',
'maxTime': '9:00pm',
'disableTimeRanges': disableTime
}
);
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
如果示例中的data
是JSON字符串,請不要使用makeArray
。 請改用JSON.parse(data)
。 makeArray
需要一個對象,而不是字符串。
請注意,JSON必須是有效的JSON,這意味着所有字符串都必須包含在雙引號中,並帶有正確的轉義內容和正確的方括號。 通過JSON驗證程序運行它,以驗證您的腳本正在接收有效的JSON。
您可以使用getJSON(),因為您的頁面正在返回JSON。 getJSON將自動解析JSON字符串。
$.getJSON('yourURL', function (disableTime) {
$("#InterviewTime").timepicker(
{
'minTime': '7:00am',
'maxTime': '9:00pm',
'disableTimeRanges': disableTime
}
);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.