json使用Ajax和MVC3解析错误

时间:2012-06-29 23:12:16

标签: ajax json asp.net-mvc-3 parsing

这是我第一次使用Ajax Json帖子。

我现在有以下脚本代码:

<script type="text/javascript">
$(document).ready(function () {
    // If the button is clicked, redirect to a controller action, send the data, and show
    // a view with the changes. 
    $('#submitDiffs').click(function () {
        var requirementNumberData = "@Model.FirstOrDefault().Requirement.RequirementNumber";

        var data = [];
        $('table tr').children('td').children('#selected :checked').each(function (i, element) {
            var el = $(element);
            data[i] = el.parent().siblings(':eq(1)').html();
        });

        diffParameters = GetDifferenceParameters(data);
        var jsonData = JSON.stringify(diffParameters, null, 2);

        $.ajax({
            url: '/Requirements/Differences',
            type: 'POST',
            data: jsonData,
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            // callback handler that will be called on error 
            success: function (response) {
                alert("Ajax call made successfully!!!");
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status + '\n\r' + xhr.responseText);
                alert(thrownError);
            }     

        });
    });

    function GetDifferenceParameters(data) {
        var requirementNumber = "@Model.FirstOrDefault().Requirement.RequirementNumber";
        var oldRequirement = data[1];
        var newRequirement = data[0];

        return { 
            RequirementNumber: requirementNumber,
            OldRequirement: oldRequirement,
            NewRequirement: newRequirement
        };
    }
});

此代码发布到MVC3控制器,代码如下:

[HttpPost]
public ActionResult Differences(RequirementDifferenceViewModel model)
{
    HtmlDiff diff = new HtmlDiff(model.OldRequirement, model.NewRequirement);
    model.ContentDifference = diff.Build();

    return View(model);
}

以下是视图模型:

public class RequirementDifferenceViewModel
{
    public string RequirementNumber { get; set; }
    public string OldRequirement { get; set; }
    public string NewRequirement { get; set; }
    public string ContentDifference { get; set; }
}

如果我省略了jSON.stringify,则控制器操作不会被执行,我收到500错误。如果我使用stringify,则会获得200状态,但是会向AJAX返回jSON解析错误。在这两种情况下,都会将确切的jSON字符串发送到AJAX调用。

这是我从Firebug中复制的jSON字符串:

{
  "RequirementNumber": "PFSNET-UC12-008",
  "OldRequirement": "\n                <p class=\"Bullet1\"><span style=\"font-size:10.0pt;font-family:Wingdings;\nfont-weight:normal\">r<span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp; </span></span><span lang=\"X-NONE\">[PFSNET-UC12-008] – Undo/redo will be supported for Expert\nAssistant. The details can be found in the use case for Undo/Redo.</span>&nbsp; </p> \n\n <p class=\"Bullet2\"><span style=\"font-family:Wingdings;font-weight:\nnormal\" lang=\"X-NONE\">§<span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp; </span></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-05-18T11:06\">A</ins></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-05-18T08:36\">n ‘Undo\nLast Action’ button will </ins></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-05-18T11:06\">also </ins></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-05-18T08:36\">be available</ins></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-05-18T11:05\"> for\nselect products</ins></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-05-18T08:36\">.&nbsp; See\nUC12-</ins></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-05-29T14:10\">229</ins></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-05-18T08:36\"> for\nadditional information.</ins></span></p> \n\n <p class=\"MsoNormal\">&nbsp;</p> \n\n\n            ",
  "NewRequirement": "\n                <p class=\"Bullet1\"><span style=\"font-size:10.0pt;font-family:Wingdings;\nfont-weight:normal\">r<span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp; </span></span><span lang=\"X-NONE\">[PFSNET-UC12-008] – Undo/redo will be supported for Expert\nAssistant. The details can be found in the use case for Undo/Redo.</span>&nbsp; </p> \n\n <p class=\"Bullet2\"><span style=\"font-family:Wingdings;font-weight:\nnormal\" lang=\"X-NONE\">§<span style=\"font:7.0pt &quot;Times New Roman&quot;\">&nbsp; </span></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-05-18T11:06\">A</ins></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-05-18T08:36\">n ‘Undo\nLast Action’ button will </ins></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-05-18T11:06\">also </ins></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-05-18T08:36\">be available</ins></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-05-18T11:05\"> </ins></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-06-20T12:34\">on </ins></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-06-20T12:42\">the\nAdvanced Expert Assistant screen.&nbsp; </ins></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-05-18T08:36\">See\nUC12-</ins></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-05-29T14:10\">229</ins></span><span class=\"msoIns\"><ins cite=\"mailto:Michelle%20Reini%20Hotchkiss\" datetime=\"2012-05-18T08:36\"> for\nadditional information.</ins></span></p> \n\n <p class=\"MsoNormal\">&nbsp;</p> \n\n\n            "
}

我将此字符串放入jSON验证器网站并通过:[http://jsonformatter.curiousconcept.com/]

确切的解析错误是: SyntaxError:JSON.parse:意外字符

任何帮助将不胜感激!

编辑2:

事实证明,解析错误是AJAX成功处理程序无法正确解析响应的结果。我仍然试图弄清楚这一部分。

执行Success事件后,代码执行会立即跳转到Error事件。

2 个答案:

答案 0 :(得分:1)

如果你在浏览器中运行它,例如firefox或chrome(不是ie),那么你可以检查网络帖子并查看标题。在那里,您应该能够确切地看到正在传递的信息。很可能你得到了一些你不期望的字符,这导致了解析错误。

答案 1 :(得分:0)

var requirementParameters = "{ oldRequirement: contentRecords[1], newRequirement: contentRecords[0] }";无效json

你可能正在寻找类似的东西:

var requirementParameters = {
    oldRequirement: contentRecords[1],
    newRequirement: contentRecords[0]
};

这会在您的字段中创建一个匿名对象。旧代码只是一个字符串,你再次JSON.stringify'。