问题
I am using jQuery fullcalendar plugin , I have tried altering this many different ways from answers to other questions with no luck, here is my jQuery:
$(document).ready(function () {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#calendar').fullCalendar({
theme: true,
aspectRatio: 3,
height: 1000,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
events: function (start, end, callback) {
$.ajax({
type: "POST",
url: "Default.aspx/GetEvents",
data: "{'userID':" + "'B473795D-306A-4718-804B-2813884D5B48'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (doc) {
var events = [];
var obj = $.parseJSON(doc.d);
var res = unescape(obj);
$(res).find('event').each(function () {
events.push({
title: $(this).attr('title'),
start: $(this).attr('start') // will be parsed
});
});
callback(events);
}
});
}
});
});
Here is my response :
{"d":"[{ \"title\" : \"circleJerk\", \"start\" : \"2012-06-22\" }, { \"title\" : \"BangTheWife\", \"start\" : \"2012-06-15\" , \"end\" : \"2012-06-23\" } ]"}
回答1:
Your return type from your method GetEvents
is string
isn't it?
Try returning a List<Event>
(or whatever your object is called) and then you don't need to go through the mess of unescaping a JSON string.
$.ajax({
type: "POST",
url: "Default.aspx/GetEvents", //return type List<Event>
data: "{'userID':" + "'B473795D-306A-4718-804B-2813884D5B48'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (doc) {
//doc.d = [Event,Event,Event] (no processing needed)
callback(events);
}
});
In response to your comment, a method with return type of List<> will look like :
[{"title": "sometitle", "start": "yourData"},{"title":"someTitle2", "start":"yourStart2"}]
Translating ASP.NET ASMX webmethod DateTime
serialization to JavaScript Date
object:
DateFromASPNET = function (sNetDate) {
if (sNetDate == null) return;
var r = /\/Date\(([0-9]+)\)\//i
var matches = sNetDate.match(r);
if (matches.length == 2) {
return new Date(parseInt(matches[1]));
}
else {
return sNetDate;
}
}
回答2:
The problem is that AJAX is aysnchronous so by passing a function to events
option, nothing is returned due to the AJAX call.
Use the built in AJX methods of the plugin by simply passing a ajax options to eventsources
option.
From Docs: http://arshaw.com/fullcalendar/docs/event_data/events_json_feed/
$('#calendar').fullCalendar({
eventSources: [
// your event source
{
url: "Default.aspx/GetEvents",
contentType: "application/json; charset=utf-8",
type: 'POST',
data: "{'userID':" + "'B473795D-306A-4718-804B-2813884D5B48'}"
}
]
});
EDIT: can also pass single event source ajax options object to events
option per docs
来源:https://stackoverflow.com/questions/11166355/jquery-isnt-parsing-json-response-properly