简体   繁体   中英

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).

Here is the 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).

Here is the cshtml page that I point AJAX to:

@{
    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.
  3. I am still always getting the alert message that runs only under the "error: function()" option of the $.ajax call.
  4. I am getting no white space either before or after the entire jsonString (not that that probably matters).
  5. I am in a WebMatrix, C#, asp.net-webpages environment.
  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. 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.

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

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

Another thing to check is that your JSON passes validation. Copy-Paste your JSON result in a JSON validator and make sure it passes. (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

$.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).

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.

Also, I didn't find it necessary to add the Response.AddHeader("Content-Type","application/json"); line, even though I am using $.ajax instead of $.getJSON

Again, thanks to everyone for your help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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