jQuery JSON 发布:传入的对象无效,应为“:”或“}”

jQuery JSON Posting: Invalid object passed in, ':' or '}' expected

当我尝试 post JSON 到服务器端功能时,出现此错误

Invalid object passed in, ':' or '}' expected

我正在使用 ckeditor,通过这种方式我可以从 ckeditor 获取数据。

var ckEditorCtrl = GetClientID("CKEditor1").attr("id");
var newcontent = getEditorContents(ckEditorCtrl.toString());

function GetClientID(id, context) {
    var el = $("#" + id, context);
    if (el.length < 1)
        el = $("[id$=_" + id + "]", context);
    return el;
}

function getEditorContents(ename) {
    if (CKEDITOR.instances[ename])
        return CKEDITOR.instances[ename].getData();

    var e = $("textarea[id$='" + ename + "']")[0];
    if (e)
            return e.value;

    return false;
}

HTML我正在尝试post从ckeditor中捕获如下

<img alt="" src="https://shop.bba-reman.com/wp-content/uploads/2017/05/Toyota-Auris-gearbox-actuator-1-300x300.jpg" style="width: 300px; height: 300px;" /><br />
<br />
We can <strong>REPAIR </strong>your Toyota Auris gearbox actuator

这样我就可以post收集数据了。这是代码

$.ajax({
    type: "POST",
    url: "/abcpage.aspx/contentinsert",
        //data: '{"CID":"' + $("[id$='txtContentID").val() + '","CTitle":"' + $("[id$='txtTitle").val() + '","CDesc":"' + $("[id$='txtDesc").val() + '","CKey":"' + $("[id$='txtKeywords").val() + '","CBody":"' + newcontent + '"}',
        data: '{"CID":"' + $("#txtContentID").val() + '","CTitle":"' + $("#txtTitle").val() + '","CDesc":"' + $("#txtDesc").val() + '","CKey":"' + $("#txtKeywords").val() + '","CBody":"' + newcontent + '","OldBody":"' + oldcontent + '"}',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
        InsertSuccess(msg);
        ComboLoad();
        HideProgressAnimation();

    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        var jsonError = JSON.parse(XMLHttpRequest.responseText);
        alert(jsonError.Message);
        ComboLoad();
        HideProgressAnimation();
    }
});

我会在 Ajax 请求之前执行此操作:

var data = {};

data.CID = $("#txtContentID").val();
data.CTitle = $("#txtTitle").val();
data.CDesc = $("#txtDesc").val();
data.CKey = $("#txtKeywords").val();
data.CBody = newcontent;
data.OldBody = oldcontent;

然后:

$.ajax({
  data: JSON.stringify(data),
  // ...

这比搞乱所有这些引号要容易得多。

Invalid object passed in, ':' or '}' expected

是由 ASP.NET 用来反序列化 JSON 的 JavaScriptSerializer 抛出的 ArgumentException。该错误意味着您的 JSON 格式不正确。例如,可能存在杂散引号或缺少大括号。

我们可以用这个简单的程序来复制错误,该程序试图反序列化一个 JSON 字符串,其中有一个额外的错误双引号:

void Main()
{
    var js = new JavaScriptSerializer();
    string invalidJson = "{\"Testing\":\"\"test\"}";
    js.Deserialize<Test>(invalidJson);
}

public class Test
{
    public string Testing { get; set; }
}

以上 抛出 相同的错误消息。有效 JSON 不会产生任何错误:

string invalidJson = "{\"Testing\":\"test\"}";