[英]Passing JSON object and Javascript Variable through AJAX
Im trying to pass a JSON object, and 2 javascript arrays in the same AJAX call. 我试图在同一AJAX调用中传递JSON对象和2个javascript数组。
I keep recieving this error 我一直收到这个错误
System.ArgumentException: Invalid JSON primitive: object
I believe this may be to do with the different types of variables being passed. 我相信这可能与传递的不同类型的变量有关。
Any obvious errors you can spot? 您可以发现任何明显的错误吗?
Thanks 谢谢
var requestData = {
"deptCode": userVar,
"roundID": parseInt(roundIDVar),
"moduleCode": moduleCodeVar,
"priority": parseInt(priorityVar),
"day": parseInt(dayVar),
"start": parseInt(timeVar)-8,
"length": parseInt(lengthVar),
"weeks": weeksNum,
"capacity": parseInt(studentsVar),
"type": roomTypeVar,
"otherReqs": otherReqs
};
var obj = JSON.stringify(requestData);
$.ajax({
type: 'POST',
url: '/create/Submit',
error: function (xhr, ajaxOptions, thrownError) {
alert("Submitting Failed. Please Reload and Try Again.");
},
data: {JSONdata:obj,weeks:weeksVar,facilities:facilitiesValue },
datatype: 'html',
contentType: 'application/json',
processData: false,
async:false,
success: function (data) {
alert(data);
}
});
Controller 调节器
public ActionResult Submit(request JSONdata, String[] Weeks, String[] facilities) {
ViewBag.module = JSONdata.weeks;
if(JSONdata.otherReqs==null){
JSONdata.otherReqs = "None";
}
JSONdata.sent = 1;
JSONdata.status = 0;
JSONdata.viewed = 0;
JSONdata.booked = 0;
db.requests.Add(JSONdata);
try
{
// Your code...
// Could also be before try if you know the exception occurs in SaveChanges
db.SaveChanges();
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
if(Convert.ToInt16(JSONdata.weeks)==1){
for (var i = 0; i < Weeks.Length; i++) {
weeks_request newWeek = new weeks_request();
newWeek.week = Convert.ToInt16(Weeks[i]);
newWeek.requestID = JSONdata.requestID;
db.weeks_request.Add(newWeek);
db.SaveChanges();
}
}
return View();
}
Try with traditional: true in your ajax call. 尝试使用传统:在您的ajax调用中为true。
$.ajax({
type: 'POST',
url: '/create/Submit',
error: function (xhr, ajaxOptions, thrownError) {
alert("Submitting Failed. Please Reload and Try Again.");
},
data: {JSONdata:obj,weeks:weeksVar,facilities:facilitiesValue },
datatype: 'html',
contentType: 'application/json',
processData: false,
async:false,
traditional: true,
success: function (data) {
alert(data);
}
}); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.