私のajax関数:
function fetchData(varUrl, varFunc, varData) {
if (varData == undefined) varData = "";
var options = {
type: "POST",
url: varUrl,
data: varData,
contentType: "application/json;charset=utf-8",
dataType: "json",
timeout: 8000,
cache: false,
beforeSend: ShowLoading(),
success: varFunc,
complete: HideLoading(),
error: function (x, t, m) {
if (t === "timeout") {
alert("got timeout");
} else {
alert(t+"\r\n\r\n"+m);
}
}
};
//execute the ajax call and get a response
var request = $.ajax(options);
}
function funcA(data){
$.each(data, function (i, item) {...}
}
function funcB(data){
$.each(data, function (i, item) {...}
}
C# コード:
public ActionResult AjaxA()
{
try
{
using (var db = new MvcContext())
{
var history = from h in db.Histories.Where(h => h.Id == 2)
return this.Json(history.ToList());
}
}
catch(Exception)
{
return this.Json("");
}
}
public ActionResult AjaxB()
{
var history = new List<MyDataType>();
history.Add( new MyData(...));
...
history.Add( new MyData(...));
return this.Json(history);
}
1) fetchData("AjaxA", funcA) を使ってデータを取得すればOK
2) fetchData("AjaxB", funcB) を使用してデータを取得すると、失敗してエラーが発生します
JSON.parse: 予期しない文字エラー
ただし、この場合でも、firebug は適切な json データを取得できます。
json データ [{"x":39,"y":115.5,"Data":16.743013706957576},{"x":39.5,"y":115.5,"Data":12.353 109643128887}]