简体   繁体   English

为什么我的$ .ajax调用不会从cshtml文件返回一个json对象?

[英]Why won't my $.ajax call return a json object from a cshtml file?

I have this jquery that uses ajax in an attempt to return a json object, but I am no pro at ajax, though I have used it before with json, only I was loading a json file and not trying to return a string from a cshtml page that queries a database for information (as I am doing here). 我有这个jquery使用ajax试图返回一个json对象,但我不是ajax的专业人士,虽然我之前使用过json,只是我正在加载一个json文件而不是试图从cshtml返回一个字符串查询数据库以获取信息的页面(正如我在这里所做的那样)。

Here is the jQuery: 这是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!");
    }
});

(Also I have tried "application/json; charset=UTF-8" as the contentType, but it changes no behavior). (我也试过“application / json; charset = UTF-8”作为contentType,但它没有改变任何行为)。

Here is the cshtml page that I point AJAX to: 这是我指向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("~/");
    }
}

It is very important to note a couple of things: 注意以下几点非常重要:

  1. I get no server-side error or error code. 我没有服务器端错误或错误代码。
  2. I have written the output to a simple .txt file to test the contents, and by pasting it into jsonLint (found here: http://jsonlint.com/ ) I was easily able to determine that this is, indeed, valid json syntax. 我已经将输出写入一个简单的.txt文件来测试内容,并将其粘贴到jsonLint(在这里找到: http ://jsonlint.com/)我很容易确定这确实是有效的json语法。
  3. I am still always getting the alert message that runs only under the "error: function()" option of the $.ajax call. 我仍然总是收到仅在$ .ajax调用的“error:function()”选项下运行的警报消息。
  4. I am getting no white space either before or after the entire jsonString (not that that probably matters). 我在整个jsonString之前或之后都没有获得空格(不是那可能很重要)。
  5. I am in a WebMatrix, C#, asp.net-webpages environment. 我在WebMatrix,C#,asp.net-webpages环境中。
  6. My only two suspicions are 1) The dataType and/or contentType is not set correctly, or 2) The last time I had to use ajax for json (targeting an actual .json file) I had to change a setting in "IIS Express" to allow it to receive data from json files, however, I thought that this was only needed if actually using ajax to parse a json "file" and not just json data. 我唯一的两个怀疑是1) dataType和/或contentType没有正确设置,或者2)我最后一次使用ajax用于json(针对实际的.json文件)我不得不更改“IIS Express”中的设置允许它从json文件接收数据,但是,我认为只有在实际使用ajax解析json“文件”而不仅仅是json数据时才需要这样做。 Also, no matter where I look, I can't seem to find this resource anymore. 而且,无论我在哪里,我似乎都无法找到这个资源。
  7. The textStatus and error parameter values are: textStatus: parsererror error: SyntaxError: Unexpected token & but this doesn't seem to throw any red flags in my mind, because I know that the json syntax by itself checks out okay. textStatus和error参数值是: textStatus:parsererror error:SyntaxError:意外的令牌&但是这似乎没有在我的脑海中抛出任何红色标志,因为我知道json语法本身可以检查出来。

Thanks to everyone for all of your help. 感谢大家的帮助。 I believe I have found the issue (the unexpected ampersand token finally made a light bulb go on in my head). 我相信我已经找到了这个问题(意想不到的&符号终于让我的头脑中出现了一个灯泡)。 I have added the answer to this page, in the event that it may help someone else in the future. 我已经在此页面中添加了答案,以防将来可能对其他人有所帮助。

I've had a similar issue, 我有类似的问题,

I've solved it by heading a header in the top of the .cshtml file in WebMatrix 我已经通过标题WebMatrix中.cshtml文件顶部的标题解决了这个问题

@{
        Response.AddHeader("Content-Type","application/json");
}

Another thing to check is that your JSON passes validation. 要检查的另一件事是您的JSON通过验证。 Copy-Paste your JSON result in a JSON validator and make sure it passes. 将JSON结果复制粘贴到JSON验证器中并确保它通过。 (You already did that, I'd like future readers of this question to see this). (你已经这样做了,我希望这个问题的未来读者能够看到这一点)。

Here is sample code you can grab your JSON with 以下是您可以获取JSON的示例代码

$.getJSON("/AJAX Pages/Compute_Calendar_Events.cshtml").done(function(result){
    alert("Success!");
    console.log(result);
}).fail(function(){
    alert("Error loading");
});

For me, the problem came as a result of razor's automatic HTML encoding (thus turning many characters into their &...; HTML encoded equivalents). 对我来说,问题是由于剃刀的自动HTML编码(因此将许多字符转换为他们的&...; HTML编码的等价物)。

Thus instead of writing @jsonString I needed to be writing @Html.Raw(jsonString) thus bypassing (as I intended originally) any further encoding that could warp the json syntax. 因此,我不需要编写@jsonString而是编写@Html.Raw(jsonString)从而绕过(如我原先的意图)任何可能扭曲json语法的进一步编码。

Also, I didn't find it necessary to add the Response.AddHeader("Content-Type","application/json"); 另外,我没有发现有必要添加Response.AddHeader("Content-Type","application/json"); line, even though I am using $.ajax instead of $.getJSON 虽然我使用的是$.ajax而不是$.getJSON

Again, thanks to everyone for your help! 再次感谢大家的帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM