jQuery/JSON 错误“语法错误:JSON.parse:意外字符”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16967289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:10:05  来源:igfitidea点击:

jQuery/JSON Error "SyntaxError: JSON.parse: unexpected character"

jqueryasp.netjsonasp.net-mvc-4

提问by Partha

I am working on MVC4 and trying to pass values form view to controller using JQuery and JSON. The query is extracting values of checkboxes inside a grid. Following is the code:

我正在研究 MVC4 并尝试使用 JQuery 和 JSON 将值表单视图传递给控制器​​。该查询正在提取网格内复选框的值。以下是代码:

<script type="text/javascript">
function DeleteCustomer() {
    var temp = "";
    var id = "";

    if (confirm("Are you sure to delete records?")) {
        $('#myGrid table tr').each(function () {
            if ($(this).find("input[id*='assignChkBx']").length > 0) {
                if ($(this).find("input[id*='assignChkBx']")[0].checked == true) {
                    temp = $(this).find("input[id*='assignChkBx']").val();
                    if (temp != "" || temp != null) {
                        id = id + " " + temp;
                        temp = "";
                    }
                } // End of Loop
            }
        }); //End of each Loop
        $.ajax({
            url: "Customer/DeleteCustomeByID",
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            dataType: "json",
            data: "{'CustomerID':'" + id + "'}",
            success: function (data) {
                //alert('Records deleted');
                $('#lblMessage').html('Records Deleted');
            },
            error: function (xhr, textStatus, err) {
                alert('Error: ' + err);
                //$('#lblMessage').html(err);
            }
        });
    }
}

My html code is following:

我的 html 代码如下:

<input type="button" id="btnDelete" value="Delete" title="Delete" onclick="DeleteCustomer()" style="color: Gray" />



@{
    WebGrid grid = new WebGrid(Model, rowsPerPage: 15, ajaxUpdateContainerId: "myGrid");
}
@grid.GetHtml(
    fillEmptyRows: false,
    alternatingRowStyle: "alternate-row",
    headerStyle: "grid-header",
    footerStyle: "grid-footer",
    mode: WebGridPagerModes.All,
    firstText: "<< First",
    previousText: "< Prev",
    nextText: "Next >",
    lastText: "Last >>",
    columns: new[] {
        grid.Column("", format: @<text><input class="check-box" type="checkbox" id="assignChkBx" value="@item.CustomerID" /></text>),
        grid.Column("CustomerID", "CustomerID", canSort: true),
        grid.Column("CompanyName", "Company Name", canSort: true),
        grid.Column("ContactName", "Contact Name", canSort: true),
        grid.Column("Address", "Address", canSort: false),
        grid.Column("City", "City", canSort: true),
        grid.Column("", 
                    header: "Actions",
                    format: @<text>
                    @Html.ActionLink("Edit",   "Edit",   new { id=item.CustomerID} )
                    @Html.ActionLink("Delete", "Delete", new { id=item.CustomerID} )
                    </text>
        )
})

When I click on delete button the jquery mentioned above will take the selected values to the controller. The controller code is written below:

当我单击删除按钮时,上面提到的 jquery 会将选定的值带到控制器。控制器代码如下:

[HttpPost]
    public ActionResult DeleteCustomeByID(string CustomerID)
    {
        Customer customer = new Customer();
        try
        {
            if (ModelState.IsValid)
            {
                string[] values = CustomerID.Split(' ');

                for (int i = 1; i <= values.Length - 1; i++)
                {
                    if (values[i].ToString().Trim() != "" || values[i].ToString() != null)
                    {
                        customer = db.Customers.Find(values[i].ToString());
                        db.Customers.Remove(customer);
                        db.SaveChanges();
                    }
                }
                return RedirectToAction("Index");
            }
            return View(customer); // Error in Model, if any
        }
        catch (DbEntityValidationException dbEx)
        {
            foreach (var validationErrors in dbEx.EntityValidationErrors)
            {
                foreach (var validationError in validationErrors.ValidationErrors)
                {
                    Trace.TraceInformation("Class: {0}, Property: {1}, Error: {2}",
                        validationErrors.Entry.Entity.GetType().FullName,
                        validationError.PropertyName,
                        validationError.ErrorMessage);
                }
            }

            throw new Exception();  // You can also choose to handle the exception here...
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

When I click on the delete button, the values go to controller and delete records. But the problem is, after deleting records when it back to controller, I am getting the following error: "SyntaxError: JSON.parse: unexpected character" for FireFox, "json parse error unrecognized token '< '" for Safari and "Error: object error." I search various sites and try various solutions. But nothing is working. I am using Northwind db.

当我单击删除按钮时,值会转到控制器并删除记录。但问题是,当它返回控制器时删除记录后,我收到以下错误:FireFox 为“ SyntaxError: JSON.parse: unexpected character”,Safari为“ json parse error unrecognized token '< '”和“ Error:对象错误。”我搜索了各种网站并尝试了各种解决方案。但没有任何效果。我正在使用 Northwind 数据库。

Thanks in advance.

提前致谢。

Partha

帕塔

回答by StriplingWarrior

According to the docs, the following property:

根据docs,以下属性:

dataType: "json"

... tells jQuery the type of data you're expecting back from the server. Then your action is returning HTML. So when jQuery tries parsing the JSON it's expecting, it runs into HTML, and gives you this error.

... 告诉 jQuery 您期望从服务器返回的数据类型。那么您的操作将返回 HTML。因此,当 jQuery 尝试解析它期望的 JSON 时,它会运行到 HTML 中,并给您这个错误。

Either change the action to return a JsonResult, or set your dataTypeto "html".

更改操作以返回 a JsonResult,或将您dataType"html".

回答by Kirk B.

Not sure, but I did notice you're not passing JSON in your $.ajax call... Try:

不确定,但我确实注意到您没有在 $.ajax 调用中传递 JSON...尝试:

data: JSON.stringify({CustomerID: id }),
...

JSON uses double quotes around the member names.

JSON 在成员名称周围使用双引号。

回答by prosa

After two day of searching, testing and debugging for a solution to this crazy error, I found that the problem was the jquery library. I was starting a new project so I choose the recent jquery-1.10.2.js, and got the error. Tried jquery-1.9.1.js, and also got the error. But when I tested with jquery-1.5.2.js, the success function worked fine and no error was throw.

经过两天的搜索,测试和调试以解决这个疯狂错误的解决方案,我发现问题出在jquery库上。我正在开始一个新项目,所以我选择了最近的 jquery-1.10.2.js,并得到了错误。试过jquery-1.9.1.js,也报错。但是当我使用 jquery-1.5.2.js 进行测试时,success 函数运行良好并且没有抛出错误。