[英]Passing JSON object and Javascript Variable through AJAX
我試圖在同一AJAX調用中傳遞JSON對象和2個javascript數組。
我一直收到這個錯誤
System.ArgumentException: Invalid JSON primitive: object
我相信這可能與傳遞的不同類型的變量有關。
您可以發現任何明顯的錯誤嗎?
謝謝
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);
}
});
調節器
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();
}
嘗試使用傳統:在您的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.