javascript - Ajax 调用失败并出现错误“SyntaxError: JSON.parse Error: Unexpected input at position:0”
问题描述
我在使用 Ajax Post 方法从视图中成功调用我的控制器时遇到问题。
这是ajax调用:
var Model =
{
Ration: "123",
Batch: "2323",
IngredientAmountList: "34",
InputAmount: "35",
RationTotalWeight:"55"
};
$.ajax({
url: '@Url.Action("AjaxCall", "Producer")',
type: "POST",
data: JSON.stringify(Model),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log("success");
console.log(data);
console.log(data.length);
},
failure: function (data) {
console.log("failure");
},
error: function (jqxhr, textStatus, errorThrown) {
console.log(jqxhr);
console.log(textStatus);
console.log(errorThrown);
},
});
这是接收 Ajax 调用的 Controller 方法:
[HttpPost]
public JsonResult AjaxCall()
{
//var modelTest = Model;
return new JsonResult();
}
Web 浏览器将从 ajax 方法错误函数中打印出错误。令我感兴趣的是,如果在控制器中的 AjaxCall() 上设置了断点,它将命中断点。如果给 AjaxCall() 一个字符串参数 AjaxCall(string test){} 它仍然会命中断点并且仍然失败。如果 AjaxCall() 被赋予模型参数,就像我最终想要做的那样,即 AjaxCall(MyModel model){} 它甚至不会命中控制器中的断点。
在 ajax 调用中传递的模型拥有实际模型的所有公共 getter/setter 属性。
ajax API 打印出来的错误是“SyntaxError: JSON.parse Error: Unexpected input at position:0”,这也是我在网上找不到的东西。
感谢您提供任何可能的建议
解决方案
试试这样:
var Model =
{
Ration: "123",
Batch: "2323",
IngredientAmountList: "34",
InputAmount: "35",
RationTotalWeight:"55"
};
$.ajax({
url: '@Url.Action("AjaxCall", "Producer")',
type: "POST",
dataType: "json",
data: { myAjaxModel: Model }, //Make sure data holds name of parameter passed to controller method
//I removed the contentType and use ajax's default object type, pass the model as a Model object to controller
success: function (data) {
const jsonResult = JSON.parse(data); //parse the response
console.log("success");
console.log(data);
console.log(data.length);
},
failure: function (data) {
console.log("failure");
},
error: function (jqxhr, textStatus, errorThrown) {
console.log(jqxhr);
console.log(textStatus);
console.log(errorThrown);
},
});
//Changed this to return a string, which is the json version of model
[HttpPost]
public string AjaxCall(Model myAjaxModel)
{
var modelTest = myAjaxModel;
//Create a javascript serializer to serialize your model
System.Web.Script.Serialization.JavascriptSerializer jss = new System.Web.Script.Serialization.JavascriptSerializer();
//Do your model updating, then return the updated version
//Return a Json version of the model
return jss.Serialize(modelTest);
}
推荐阅读
- python - 如何评估 kmeans 算法的测试误差
- c# - 如何有效地将霍夫曼树和编码二进制字符串存储到文件中?
- javascript - 禁用未来日期引导 vue datepicker
- c++ - 为什么我的 C++/Qt 程序在单击相关按钮后不显示标签对象?
- html - MatRipple 继续显示无论如何
- python - Mac OS Big Sur 更新导致 django 1.11 的 pip 安装要求出现 cffi 错误
- python - 如何使用 Selenium Python 单击接受按钮
- php - 我必须在 Javascript 中调用 php 变量但在字符串中
- c# - 如何打印随机数的总和?C#
- javascript - 如何加速 SVG 变形