JSON 解析错误语法错误意外结束输入 [英] JSON parsing error syntax error unexpected end of input

查看:123
本文介绍了JSON 解析错误语法错误意外结束输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了以下代码

function pushJsonData(productName) {
    $.ajax({
        url: "/knockout/SaveProduct",
        type: "POST",
        contentType: "application/json",
        dataType: "json",
        data: " { "Name" : "AA" } ",
        async: false,
        success: function () {
            loadJsonData();   
        },
        error: function (jqXHR, textStatus, errorThrown) {
          alert(textStatus + " in pushJsonData: " + errorThrown + " " + jqXHR);
        }
    });
}

请注意,我对数据值进行了硬编码.数据被推送到数据库中.但是,我不断收到错误

Notice that I hard coded the data value. The data get pushed into the database fine. However, I keep getting the error

解析错误语法错误意外结束输入

parsing error syntax error unexpected end of input

我确信我的数据采用正确的 JSON 语法.当我在 Chrome 检查器的网络上检查时,saveProduct 请求显示数据正确.

I am sure my data is in correct JSON syntax. When I checked with on Network of Chrome inspector the saveProduct request showed the data is correct.

{ "Name": "AA" }

此 POST 请求没有响应.所以我对解析错误的来源一无所知.我尝试使用 FireFox 浏览器.同样的事情发生了.

This POST request did not have response. So I am clueless as to where the parse error was coming from. I tried using FireFox browser. the same thing happened.

任何人都可以给出一些错误的想法吗?

Can anyone give some idea as to what is wrong?

谢谢,

附言这是控制器代码

namespace MvcApplJSON.Controllers
{
    public class KnockoutController : Controller
    {
        //
        // GET: /Knockout/

        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public JsonResult GetProductList()
        {
            var model = new List<Product>();
            try
            {
                using (var db = new KOEntities())
                {
                    var product = from p in db.Products orderby p.Name select p;
                    model = product.ToList();
                }
            }
            catch (Exception ex)
            { throw ex; }
            return Json(model, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public void SaveProduct (Product product)
        {
            using (var db = new KOEntities())
            {
                db.Products.Add(new Product { Name = product.Name, DateCreated = DateTime.Now });
                db.SaveChanges();
            }
        }
    }
}

推荐答案

我不能确定是什么问题.可能是一些不好的字符,可能是你在开头和结尾留下的空格,不知道.

I can't say for sure what the problem is. Could be some bad character, could be the spaces you have left at the beginning and at the end, no idea.

无论如何,你不应该像你所做的那样将你的 JSON 硬编码为字符串.相反,将 JSON 数据发送到服务器的正确方法是使用 JSON 序列化程序:

Anyway, you shouldn't hardcode your JSON as strings as you have done. Instead the proper way to send JSON data to the server is to use a JSON serializer:

data: JSON.stringify({ name : "AA" }),

现在在服务器上还要确保你有合适的视图模型来接收这个输入:

Now on the server also make sure that you have the proper view model expecting to receive this input:

public class UserViewModel
{
    public string Name { get; set; }
}

和相应的动作:

[HttpPost]
public ActionResult SaveProduct(UserViewModel model)
{
    ...
}

现在还有一件事.您已指定 dataType: 'json'.这意味着您希望服务器返回 JSON 结果.控制器操作必须返回 JSON.如果您的控制器操作返回一个视图,这可以解释您遇到的错误.当 jQuery 尝试解析来自服务器的响应时:

Now there's one more thing. You have specified dataType: 'json'. This means that you expect that the server will return a JSON result. The controller action must return JSON. If your controller action returns a view this could explain the error you are getting. It's when jQuery attempts to parse the response from the server:

[HttpPost]
public ActionResult SaveProduct(UserViewModel model)
{
    ...
    return Json(new { Foo = "bar" });
}

话虽如此,在大多数情况下,在向 ASP.NET MVC 控制器操作发出 AJAX 请求时,通常不需要设置 dataType 属性.这是因为当你返回一些特定的ActionResult(比如一个ViewResult或者一个JsonResult)时,框架会自动设置正确的Content-Type 响应 HTTP 标头.然后 jQuery 将使用此标头解析响应并将其作为参数提供给已解析的成功回调.

This being said, in most cases, usually you don't need to set the dataType property when making AJAX request to an ASP.NET MVC controller action. The reason for this is because when you return some specific ActionResult (such as a ViewResult or a JsonResult), the framework will automatically set the correct Content-Type response HTTP header. jQuery will then use this header to parse the response and feed it as parameter to the success callback already parsed.

我怀疑您在这里遇到的问题是您的服务器没有返回有效的 JSON.它要么返回了一些 ViewResult 或 PartialViewResult,要么您尝试在控制器操作中手动制作一些损坏的 JSON(显然您不应该这样做,而应该使用 JsonResult).

I suspect that the problem you are having here is that your server didn't return valid JSON. It either returned some ViewResult or a PartialViewResult, or you tried to manually craft some broken JSON in your controller action (which obviously you should never be doing but using the JsonResult instead).

我刚刚注意到的另一件事:

One more thing that I just noticed:

async: false,

请避免将此属性设置为 false.如果您将此属性设置为 false,您将在整个请求执行期间冻结客户端浏览器.在这种情况下,您可以发出正常请求.如果您想使用 AJAX,请开始考虑异步事件和回调.

Please, avoid setting this attribute to false. If you set this attribute to false you are are freezing the client browser during the entire execution of the request. You could just make a normal request in this case. If you want to use AJAX, start thinking in terms of asynchronous events and callbacks.

这篇关于JSON 解析错误语法错误意外结束输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆