我有这个 jquery,它使用 ajax 试图返回一个 json 对象,但我不是 ajax 专家,虽然我之前用过 json,只是我加载了一个 json 文件而不是试图返回一个字符串来自查询数据库信息的 cshtml 页面(正如我在这里所做的那样)。
这是 jQuery:
$.ajax({
url: "/AJAX Pages/Compute_Calendar_Events.cshtml",
async: true,
type: "GET",
dataType: "json",
contentType: "application/json",
success: function (jsonObj) {
console.log("AJAX SUCCESS!");
},
error: function (jqXHR, textStatus, error) {
alert("NO AJAX!");
}
});
(我也尝试过“application/json; charset=UTF-8”作为 contentType,但它没有改变任何行为)。
这是我将 AJAX 指向的 cshtml 页面:
@{
Layout = "";
if(IsAjax || 1==1)
{
string jsonString = "{\"events\":[";
string selectQueryString = "SELECT title, summary, eventDate FROM CalendarEvents ORDER BY eventDate ASC";
var db = Database.Open("Content");
foreach (var row in db.Query(selectQueryString))
{
jsonString += "{";
jsonString += "\"title\":" + Json.Encode(row.title) + ",";
jsonString += "\"dateNumber\":" + Json.Encode(row.eventDate.ToString().Substring(0, row.eventDate.ToString().IndexOf("/"))) + ",";
jsonString += "\"dateMonth\":" + Json.Encode(row.eventDate.ToString().Substring(row.eventDate.ToString().IndexOf("/") + 1, row.eventDate.ToString().LastIndexOf("/") - (row.eventDate.ToString().IndexOf("/") + 1))) + ",";
jsonString += "\"dateYear\":" + Json.Encode(row.eventDate.ToString().Substring(row.eventDate.ToString().LastIndexOf("/") + 1, 4)) + ",";
jsonString += "\"summary\":" + Json.Encode(row.summary);
jsonString += "},";
}
jsonString = jsonString.TrimEnd(',');
jsonString += "]}";
/*System.IO.File.Delete(Server.MapPath("~/TEST.txt"));
var outputFile = System.IO.File.AppendText(Server.MapPath("~/TEST.txt"));
outputFile.Write(jsonString);
outputFile.Close();*/
@* *@@jsonString
}
else
{
Response.Redirect("~/");
}
}
注意以下几点非常重要:
- 我没有收到服务器端错误或错误代码。
- 我已将输出写入一个简单的 .txt 文件以测试内容,并将其粘贴到 jsonLint(可在此处找到:http://jsonlint.com/),我很容易确定这确实是有效的 json 语法。
- 我仍然总是收到仅在 $.ajax 调用的“error: function()”选项下运行的警报消息。
- 我在整个 jsonString 之前或之后都没有空格(这可能并不重要)。
- 我在 WebMatrix、C#、asp.net-webpages 环境中。
- 我唯一的两个怀疑是1) dataType 和/或contentType 设置不正确,或者2) 上次我不得不对json 使用ajax(定位一个实际的 .json 文件)我不得不更改“IIS Express”中的设置以允许它从 json 文件接收数据,但是,我认为只有在实际使用 ajax 解析 json"file"而不仅仅是json 数据。另外,无论我在哪里看,我似乎都找不到这个资源。
- textStatus 和 error 参数值是:textStatus: parsererror error: SyntaxError: Unexpected token & 但这似乎并没有在我脑海中抛出任何危险信号,因为我知道 json 语法自己检查没问题。
感谢大家的帮助。我相信我已经找到了问题所在(意想不到的符号标记终于让我的脑袋亮了起来)。我已将答案添加到此页面,以防将来对其他人有所帮助。
最佳答案
我遇到过类似的问题,
我已经通过在 WebMatrix 中的 .cshtml
文件顶部添加标题来解决它
@{
Response.AddHeader("Content-Type","application/json");
}
要检查的另一件事是您的 JSON 是否通过了验证。将您的 JSON 结果复制粘贴到 JSON 验证器中并确保它通过。 (您已经这样做了,我希望这个问题的 future 读者能够看到这一点)。
这是您可以用来获取 JSON 的示例代码
$.getJSON("/AJAX Pages/Compute_Calendar_Events.cshtml").done(function(result){
alert("Success!");
console.log(result);
}).fail(function(){
alert("Error loading");
});
关于c# - 为什么我的 $.ajax 调用不会从 cshtml 文件返回 json 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16652232/