简体   繁体   中英

Ajax call successful, but error block is executing

I'm trying to save a post to my database which it does, however the ajax error block is executing. It states ok in its response though so I looked around on some of the other questions and it seemed like I wasn't returning a Json object so I tried a few things:

Creating a NameValule variable and adding ("Success","true") and converting it to Json by Json.Encode(NameValue);

Returning a string in the format of Json:"{ \\"Result\\":[{\\"Success\\":\\"true\\"}]}";

Changing the dataType to "text json" "text/json"

The error block still executes for some reason, any ideas?

//Save it all in an object to be passed in ajax 
    var Post = {
        Id: postID,
        Title: postTitle.val(),
        Author: postAuthor,
        Date: postDate,
        Content: postContent.val(),
        metaDescription: metaDescription.val(),
        metaKeywords: metaKeywords.val(),
        metaID: metaId.text(),
        Page: $(document).attr('title')
    };
//save to database 
        $.ajax({
            url: url,
            type: 'POST', 
            dataType: "text json",
            data: { data: JSON.stringify(Post) },
            success: function (result) {
                console.log("result: " + result);
                if (result == "Success") {
                   // postContent.append("<br/><p>Edit Successful!</p>");
                    alert('Edit successfull');
                   //window.location.replace(window.location.href);
                }
                else {
                    postContent.replaceWith("<div>" + result + "</div>");
                }                    
            },
            error: function (xhr, status) { 
                console.log('ajax error = ' + xhr.statusText);
            }
        });  

Here is the response page:

@using WebMatrix.Data; 
@functions{
    public string EditPost()
    {
        var db = Database.Open("StarterSite");
        var post = Request.Unvalidated["data"];
        var result = Json.Decode(post);
        var error = new System.Collections.Specialized.NameValueCollection();

        /*        Id: postID,
                    Title: postTitle,
                    Author: postAuthor,
                    Date: postDate,
                    Content: afterEdit,
                    Page: $(document).attr('title')
                    */
        if(string.IsNullOrEmpty(result["Id"]))
        {
            error.Add("Error", "Id empty");
            return Json.Encode(error);
        }
        if (string.IsNullOrEmpty(result["Author"]))
        {
            error.Add("Error", "Author empty");
            return Json.Encode(error);
        }
        if (string.IsNullOrEmpty(result["Content"]))
        {
            error.Add("Error", "Content empty");
            return Json.Encode(error);
        }
        if (string.IsNullOrEmpty(result["Date"]))
        {
            error.Add("Error", "Date empty");
            return Json.Encode(error);
        }
        //Page and Title only ones that can be empty
        var cmd = "UPDATE Posts SET ID='" + result["Id"]
                + "',Author='" + result["Author"]
                + "',Content='" + result["Content"]
                + "',Date='" + result["Date"]
                + "',Title='" + result["Title"]
                + "',Page='" + result["Page"]
                + "' WHERE ID='" + result["Id"] + "';";
        try { db.Execute(cmd); }
        catch (Exception e)
        {
            error.Add("Error",e.Message);
            return Json.Encode(error);
        }


        if (string.IsNullOrEmpty(result["metaDescription"]))
        {
            error.Add("Error", "metaDescription empty");
            return Json.Encode(error);
        }
        if (string.IsNullOrEmpty(result["metaKeywords"]))
        {
            error.Add("Error", "metaKeywords empty");
            return Json.Encode(error);
        }
        //Post was edited successfully add/update meta info
        int parseResult = 0;
        Int32.TryParse(result["metaID"], out parseResult);
        if (parseResult > 0)//metaID is supplied
        {
            cmd = "UPDATE MetaInfo SET Description='" + result["metaDescription"]
             + "',Keywords='" + result["metaKeywords"]
             + "',postID='" + result["Id"]
             + "' WHERE ID='" + result["metaID"] + "';";
        }
        else //metaID is not supplied
        {
            cmd = "INSERT INTO MetaInfo (Description,Keywords,postID) VALUES('"
            + result["metaDescription"] + "','"
            + result["metaKeywords"] + "','"
            + result["Id"] + "');";
        }
        try
        {
            db.Execute(cmd);
        }
        catch (Exception e)
        {
            error.Add("Error",e.Message);
            return Json.Encode(error);
        }
        //End Update meta info 
        error.Add("Success", "true");
        return Json.Encode(error); //"{ \"Result\":[{\"Success\":\"true\"}]}";
    }
}
 @{
 var result = EditPost(); 
 } 
 @result

Can't be sure without knowing the requirements for the url. My guess would be that the data property is the reason you're off. I'm guess Post is an object defined elsewhere. When you send your request, the server will likely interpret the data field as an object not a string. Try to change {data: JSON.stringify(Post)} to just JSON.stringify(Post)

尝试添加async:true,在类型之后输入:“ POST”,

Problem is with your JSON response.

"{ \"Result\":[{\"Success\":\"true\"}]}";

There added slashes before double quotes(").

You can see the actual error thrown by jQuery using below updated error block:

error: function (xhr, status, errorThrown ) {
        console.log(errorThrown ) 

Solution:

Remove slashes from your response try response like below:

'{ "Result":[{"Success":"true"}]}'

Hope this will help you.

Regards,

对于其他可能遇到相同问题的人,这是我最终解决的方法:只需使用Html.Raw(result)仅发送回json即可,而不发送由于某种原因而添加的多余内容。

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