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

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

问题描述

我得到了下面这段code

 函数pushJsonData(产品名称){
    $阿贾克斯({
        网址:/淘汰赛/ SaveProduct
        键入:POST,
        的contentType:应用/ JSON
        数据类型:JSON,
        数据:{\名称\:\AA \},
        异步:假的,
        成功:函数(){
            loadJsonData();
        },
        错误:函数(jqXHR,textStatus,errorThrown){
          警报(在pushJsonData:textStatus + errorThrown ++ jqXHR);
        }
    });
}
 

请注意,我很难codeD的数据值。该数据将被推入数据库的罚款。不过,我不断收到解析输入的错误语法错误意外结束错误。我相信我的数据是正确的JSON语法。当我检查了在Chrome检查网络的saveProduct要求显示的数据是正确的。

  {姓名:AA}
 

这POST请求没有回应。所以我无能,那里的解析错误来自何处。我尝试使用Firefox浏览器。同样的事情发生。

任何人都可以提供一些想法,什么是错的?

谢谢

P.S。 这里是控制器code

 命名空间MvcApplJSON.Controllers
{
    公共类KnockoutController:控制器
    {
        //
        // GET:/基因剔除/

        公众的ActionResult指数()
        {
            返回查看();
        }

        [HTTPGET]
        公共JsonResult GetProductList()
        {
            VAR模型=新的名单,其中,产品>();
            尝试
            {
                使用(VAR DB =新KOEntities())
                {
                    变种产品=从p在db.Products排序依据p.Name的选择P;
                    模型= product.ToList();
                }
            }
            赶上(例外前)
            {抛出前; }
            返回JSON(型号,JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        公共无效SaveProduct(产品产品)
        {
            使用(VAR DB =新KOEntities())
            {
                db.Products.Add(新产品{名称= product.Name,dateCreated会= DateTime.Now});
                db.SaveChanges();
            }
        }
    }
}
 

解决方案

不能肯定地说是什么问题。可能是一些不良的性格,可能是你已经离开在开始和结束时,不知道。

的空间

总之,你绝对应该永远不会被硬编码的JSON字符串像你一样。而不是JSON数据发送到服务器的正确方法是使用JSON序列化:

 数据:JSON.stringify({名字:AA}),
 

现在的服务器还请确保您有适当的视图模型能接收这个输入:

 公共类UserViewModel
{
    公共字符串名称{;组; }
}
 

和相应的操作:

  [HttpPost]
公众的ActionResult SaveProduct(UserViewModel模型)
{
    ...
}
 

现在还有一件事。您指定数据类型:JSON。这意味着,你想到的是,服务器将返回一个JSON的结果。控制器动作必须返回JSON。如果你的控制器动作返回一个视图这可以解释你所得到的错误。这是jQuery的时候尝试解析来自服务器的响应:

  [HttpPost]
公众的ActionResult SaveProduct(UserViewModel模型)
{
    ...
    返回JSON(新{美孚=酒吧});
}
 

这是说,在作出AJAX请求到ASP.NET MVC控制器操作时最casesusually你不需要设置的dataType 属性。其中的原因是因为当你返回一些特定的ActionResult(如一个ViewResult或JsonResult),该框架将自动设置正确的内容类型响应HTTP头。 jQuery将然后用这个标题来解析响应,并喂给它的参数已经解​​析成功的回调。

我怀疑你有这里的问题是,你的服务器未返回有效的JSON。它要么退回部分的ViewResult或PartialViewResult,或者你想手工工艺一些破碎的JSON在你的控制器的动作(这显然你不应该做,但使用JsonResult代替)。

天上,那我只注意到一件事,使我的眼睛流血:

 异步:假的,
 

真的吗?请,永远别再的 EVER 绝不会将此属性设置为false。我看到人们这样做一遍又一遍又一遍又一遍。这是离谱。伙计们,如果你将此属性设置为你不再做AJAX。你挡/请求杀死所有的好处,AJAX给你的整个执行过程中冻结客户端浏览器。只是使在这种情况下,一个正常的请求。不要打扰用JavaScript。如果你想要做的AJAX,然后停止在程序和顺序编程的角度来思考。在启动异步事件和回调来思考。

I got the following piece of code

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". 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" }

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?

Thanks,

P.S. Here is the controller code

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

解决方案

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.

Anyway, you should absolutely never be hardcoding your JSON as strings as you did. 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; }
}

and the corresponding action:

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

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

This being said, in most casesusually you don't need to be setting the dataType property when making AJAX request to an ASP.NET MVC controller action. The reason for that 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.

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).

Ohhhh, and one more thing that I just noticed that made my eyes bleed:

async: false,

Seriously? Please, NEVER EVER NEVER set this attribute to false. I am seeing people doing this over and over and over and over again. It's outrageous. Guys, if you set this attribute to false you are no longer doing AJAX. You are blocking/freezing the client browser during the entire execution of the request killing all the benefits that AJAX gives you. Just make a normal request in this case. Don't bother with javascript. If you want to do AJAX, then stop thinking in terms of procedural and sequential programming. Start thinking in terms of asynchronous events and callbacks.

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

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