jQuery json解析错误语法错误意外的输入结束
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20827372/
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
json parsing error syntax error unexpected end of input
提问by Shawn
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.
请注意,我对数据值进行了硬编码。数据被推送到数据库中。但是,我不断收到错误“解析错误语法错误意外的输入结束”。我确信我的数据采用正确的 JSON 语法。当我在 Chrome 检查器的网络上检查时,saveProduct 请求显示数据正确。
{ "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.
此 POST 请求没有响应。所以我对解析错误的来源一无所知。我尝试使用 FireFox 浏览器。同样的事情发生了。
Can anyone give some idea as to what is wrong?
任何人都可以给出一些关于什么是错的想法吗?
Thanks,
谢谢,
P.S. Here is the controller code
PS这是控制器代码
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();
}
}
}
}
回答by Darin Dimitrov
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.
我不能确定是什么问题。可能是一些不好的角色,可能是你在开头和结尾留下的空格,不知道。
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:
无论如何,你不应该像你所做的那样将你的 JSON 硬编码为字符串。相反,将 JSON 数据发送到服务器的正确方法是使用 JSON 序列化程序:
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:
现在还有一件事。您已指定dataType: 'json'
. 这意味着您希望服务器返回 JSON 结果。控制器操作必须返回 JSON。如果您的控制器操作返回一个视图,这可以解释您遇到的错误。当 jQuery 尝试解析来自服务器的响应时:
[HttpPost]
public ActionResult SaveProduct(UserViewModel model)
{
...
return Json(new { Foo = "bar" });
}
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.
话虽如此,在大多数情况下,dataType
在向 ASP.NET MVC 控制器操作发出 AJAX 请求时,通常不需要设置该属性。这样做的原因是因为当您返回一些特定的ActionResult
(例如 aViewResult
或 a JsonResult
)时,框架会自动设置正确的Content-Type
响应 HTTP 标头。然后 jQuery 将使用此标头解析响应并将其作为参数提供给已解析的成功回调。
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).
我怀疑您在这里遇到的问题是您的服务器没有返回有效的 JSON。它要么返回一些 ViewResult 或 PartialViewResult,要么您尝试在控制器操作中手动制作一些损坏的 JSON(显然您不应该这样做,而应该使用 JsonResult)。
One more thing that I just noticed:
我刚刚注意到的另一件事:
async: false,
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.
请避免将此属性设置为 false。如果您将此属性设置为false
您将在整个请求执行期间冻结客户端浏览器。在这种情况下,您可以发出正常请求。如果您想使用 AJAX,请开始考虑异步事件和回调。
回答by Ben
I was using a Node http
request and listening for the data
event. This event only puts the data into a buffer temporarily, and so a complete JSON is not available. To fix, each data
event must be appended to a variable. Might help someone (http://nodejs.org/api/http.html).
我正在使用 Nodehttp
请求并监听data
事件。此事件只是暂时将数据放入缓冲区,因此无法获得完整的 JSON。要修复,data
必须将每个事件附加到变量。可能会帮助某人(http://nodejs.org/api/http.html)。
回答by Vish
For me the issue was due to single quotes for the name/value pair... data: "{'Name':'AA'}"
对我来说,问题是由于名称/值对的单引号引起的...数据:“{'Name':'AA'}”
Once I changed it to double quotes for the name/value pair it works fine... data: '{"Name":"AA"}' or like this... data: "{\"Name\":\"AA\"}"
一旦我将其更改为名称/值对的双引号,它就可以正常工作... data: '{"Name":"AA"}' 或像这样... data: "{\"Name\":\" AA\"}"
回答by Developer
May be it will be useful.
可能会有用。
The method parameter name should be the same like it has JSON
方法参数名称应该与 JSON 相同
It will work fine
它会正常工作
C#
C#
public ActionResult GetMTypes(int id)
JS
JS
var params = { id: modelId };
var url = '@Url.Action("GetMTypes", "MaintenanceTypes")';
$.ajax({
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(params),
It will NOT work fine
它不会正常工作
C#
C#
public ActionResult GetMTypes(int modelId)
JS
JS
var params = { id: modelId };
var url = '@Url.Action("GetMTypes", "MaintenanceTypes")';
$.ajax({
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(params),
回答by AlexNikonov
spoiler: possible Server Side Problem
剧透:可能的服务器端问题
Here is what i've found, my code expected the responcefrom my server, when the server returned just 200 code, it wasnt enough herefrom json parser thrown the error error unexpected end of input
这是我发现的,我的代码期望来自我的服务器的响应,当服务器仅返回 200 个代码时,这还不够,因此 json 解析器抛出错误错误意外的输入结束
fetch(url, {
method: 'POST',
body: JSON.stringify(json),
headers: {
'Content-Type': 'application/json'
}
})
.then(res => res.json()) // here is my code waites the responce from the server
.then((res) => {
toastr.success('Created Type is sent successfully');
})
.catch(err => {
console.log('Type send failed', err);
toastr.warning('Type send failed');
})
回答by shaijut
Don't Return Empty Json
不要返回空的 Json
In My Case I was returning Empty Json
String in .Net Core Web API
Project.
在我的情况下,我Json
在.Net Core Web API
项目中返回空字符串。
So I Changed My Code
所以我改变了我的代码
From
从
return Ok();
To
到
return Ok("Done");
It seems you have to return some string or object.
看来您必须返回一些字符串或对象。
Hope this helps.
希望这可以帮助。
回答by apmechev
I've had the same error parsing a string containing \n
into JSON. The solution was to use string.replace('\n','\\n')
我在解析包含\n
JSON的字符串时遇到了同样的错误。解决方案是使用string.replace('\n','\\n')
回答by Pacerier
Unexpected end of input means that the parser has ended prematurely. For example, it might be expecting "abcd...wxyz"
but only sees "abcd...wxy
.
输入的意外结束意味着解析器过早结束。例如,它可能在期待"abcd...wxyz"
但只看到"abcd...wxy
。
This can be a typoerror somewhere, or it could be a problem you get when encodings are mixed across different parts of the application.
这可能是某个地方的拼写错误,也可能是在应用程序的不同部分混合编码时遇到的问题。
One example: consider you are receiving data from a native app using chrome.runtime.sendNativeMessage
:
一个示例:假设您正在使用chrome.runtime.sendNativeMessage
以下方式从本机应用程序接收数据:
chrome.runtime.sendNativeMessage('appname', {toJSON:()=>{return msg}}, (data)=>{
console.log(data);
});
Now beforeyour callback is called, the browser would attempt to parse the message using JSON.parse
which can give you "unexpected end of input" errors if the supplied byte lengthdoes not match the data.
现在,在调用回调之前,浏览器将尝试解析消息JSON.parse
,如果提供的字节长度与数据不匹配,则可能会出现“意外的输入结束”错误。
回答by Victor Michael Kosgei
I did this in Node JS and it solved this problem:
我在 Node JS 中做了这个,它解决了这个问题:
var data = JSON.parse(Buffer.concat(arr).toString());