javascript - Ajax 调用成功,但错误 block 正在执行

标签 javascript jquery json ajax

我正在尝试将帖子保存到我的数据库中,但 ajax 错误 block 正在执行。它在响应中声明“ok”,所以我环顾了一下其他一些问题,似乎我没有返回 Json 对象,所以我尝试了一些操作:

创建NameValule变量并添加("Success","true")并通过Json.Encode(NameValue)将其转换为Json;

返回Json格式的字符串:"{\"Result\":[{\"Success\":\"true\"}]}";

将数据类型更改为“text json”“text/json”

由于某种原因,错误 block 仍然执行,有什么想法吗?

//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);
            }
        });  

这是响应页面:

@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

最佳答案

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

关于javascript - Ajax 调用成功,但错误 block 正在执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32675474/

相关文章:

javascript - NVDA 在 react 更新 html dom 之前选择更改

javascript - 用于在 Typescript(或 Javascript)中生成 CSV 文件的本地分隔符

jquery - 按钮中的微调器

mysql - 从 MySQL 获取 Json 格式的 byte[]

javascript - 从 .json URL 获取数据并使用 Javascript/JQuery 将其显示在 HTML 中

javascript - useState 对象集

javascript - 无法传递数组元素来恢复表单

javascript - jQuery:将图像拖放到具有相同类的 div 内?

javascript - 如何通过jquery在外部点击时隐藏div,除了一个内部div

angularjs - JSON(嵌套结构)中的长度检测 - Angular View