[英]Invalid Character using json.parse
Using Asp.Net Core, after an ajax form submit I am returning an IActionResult from a Controller containing a Json result of my MVC Model object (Comment): 使用Asp.Net Core,在ajax表单提交后,我从Controller中返回一个IActionResult,其中包含我的MVC Model对象的Json结果(Comment):
[HttpPost]
public IActionResult AjCreate([FromForm] Comment comment)
{
// do whatever to save to the database
//....
// return a json object
return Json(comment);
//return Ok(comment);
}
The script to submit the form and handle the response is as follows: 提交表单和处理响应的脚本如下:
$(function () {
$('#submitButton').on('click', function (e) {
e.preventDefault();
var formData = $('#myForm').serialize();
console.log('before ajax: ', formData);
$.ajax({
type: 'POST',
url: 'AjCreate',
dataType: 'json',
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
data: formData,
success: function (response) {
var comment = JSON.parse(response); //<<<Invalid character error here
console.log('Success: ' + comment.commentText);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('error is:' + thrownError);
}
});
});
});
I am hoping to use JSON.parse to be able to access the 'properties' of the object returned, but the JSON.parse line causes an Invalid character error. 我希望使用JSON.parse能够访问返回的对象的'属性',但JSON.parse行导致无效字符错误。 The response body header shows the json response to be
{"id":2,"commentText":"comment 2 text","commentDate":"2111-01-01T00:00:00","userName":"Will","parentCommentId":1}
. 响应正文标题显示json响应为
{"id":2,"commentText":"comment 2 text","commentDate":"2111-01-01T00:00:00","userName":"Will","parentCommentId":1}
。 I can get this if I use JSON.stringify
instead, but how do I then access the object properties eg comment.id
? 如果我使用
JSON.stringify
,我可以得到这个,但是如何访问对象属性,例如comment.id
?
Can anyone suggest what I am doing wrong or a way around this? 任何人都可以建议我做错了什么或解决这个问题? Ultimately, I want to add elements to the page based on the returned values.
最终,我想根据返回的值向页面添加元素。
From jQuery documentation , under dataType
从jQuery 文档 ,在
dataType
"json": Evaluates the response as JSON and returns a JavaScript object.
“json”:将响应计算为JSON并返回JavaScript对象。
You've already got an object, just use it: 你已经有了一个对象,只需使用它:
success: function (response) {
console.log('Success: ' + response.commentText);
}, // ^^^^^^^^
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.