AJAX调用中返回的JSON不起作用
JSON returned in AJAX call not working
我试图通过向AJAX调用发送新插入的ID和JSON变量来检测数据库条目是否已成功输入,但它在phonegAP中不起作用,但在所有浏览器中都可以,我可以看到数据已成功插入数据库。感谢所有评论/帮助,谢谢。AJAX代码-
function InsertQnA() {
$.ajax({
url: Domain + '/Result/Create',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{"Q1":"' + Q1 + '","Q2":"' + Q2 + '","Q3":"' + Q3 + '","Q4":"' + Q4 + '","Q5":"' + Q5 + '","Q6":"' + Q6 + '","Q7":"' + Q7 + '","Q8":"' + Q8 + '","Q9":"' + Q9 + '","Q10":"' + Q10 + '","Total":"' + localStorage.getItem("Total", Total) + '","CaseStudy":"' + localStorage.getItem("CaseStudy") + '","UserId":"' + localStorage.getItem("UserId") + '","Attempts":"' + QnANumAttempts + '"}',
success: function (data) {
alert('this alert is invoked successfully');
if (data.Success == true) {
alert('this alert is not being invoked successfully');
//result id used for feedback insertion > update result entity
localStorage.setItem("ResultId", data.ResultId);
viewModel.UserId("You have successfully completed case study " + localStorage.getItem("CaseStudy") + ", please fill out the <a href='evaluation.html' target='_self'>evaluation.</a>");
}
else if (data.Success==false)
{
alert('this alert is not being invoked either');
viewModel.UserId("Your entry has not been saved, please try again.");
}
},
}).fail(
function (xhr, textStatus, err) {
console.log(xhr.statusText);
console.log(textStatus);
console.log(err);
});
}
mvc功能
//
// POST: /Result/Create
[HttpPost]
public ActionResult Create(Result result)
{
if (ModelState.IsValid)
{
result.ResultDate = DateTime.Now;
repository.InsertResult(result);
repository.Save();
if (Request.IsAjaxRequest())
{
int ResultId = result.ResultId;
try
{ //valid database entry..send back new ResultId
return Json(new { Success = true, ResultId, JsonRequestBehavior.AllowGet });
}
catch
{ // no database entry
return Json(new { Success = false, Message = "Error", JsonRequestBehavior.AllowGet });
}
}
return RedirectToAction("Index");
}
return View(result);
}
发现代码有两个问题:
1.localStorage.getItem("Total", Total)
应为localStorage.getItem("Total")
2.dataType : "json"
未明确提及。
我已经发布了相关更正。如果有帮助,可以试试这个,如果你有任何错误,也可以分享。
function InsertQnA() {
$.ajax({
url: Domain + '/Result/Create',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{"Q1":"' + Q1 + '","Q2":"' + Q2 + '","Q3":"' + Q3 + '","Q4":"' + Q4 + '","Q5":"' + Q5 + '","Q6":"' + Q6 + '","Q7":"' + Q7 + '","Q8":"' + Q8 + '","Q9":"' + Q9 + '","Q10":"' + Q10 + '","Total":"' + localStorage.getItem("Total") + '","CaseStudy":"' + localStorage.getItem("CaseStudy") + '","UserId":"' + localStorage.getItem("UserId") + '","Attempts":"' + QnANumAttempts + '"}',
dataType : "json",
success: function (data) {
alert('this alert is invoked successfully');
try {
if (data.Success == true) {
alert('this alert is not being invoked successfully');
//result id used for feedback insertion > update result entity
localStorage.setItem("ResultId", data.ResultId);
viewModel.UserId("You have successfully completed case study " + localStorage.getItem("CaseStudy") + ", please fill out the <a href='evaluation.html' target='_self'>evaluation.</a>");
}
else if (data.Success==false)
{
alert('this alert is not being invoked either');
viewModel.UserId("Your entry has not been saved, please try again.");
}
}catch(error) {
alert("This is the error which might be: "+error.message);
}
},
}).fail(
function (xhr, textStatus, err) {
console.log(xhr.statusText);
console.log(textStatus);
console.log(err);
});
}
在服务器端代码中进行这些更改。
var json = "";
try
{ //valid database entry..send back new ResultId
json = Json.Encode(new { Success = true, ResultId, JsonRequestBehavior.AllowGet });
}
catch
{ // no database entry
json = Json.Encode(new { Success = false, Message = "Error", JsonRequestBehavior.AllowGet });
}
Response.Write(json);
从我(过去两天)收集的数据来看,MVC ActionResult似乎不容易为Web应用程序提供数据。我通过用字符串方法复制ActionResult来解决这个问题,现在它工作得很好。可能不是最好的解决方案,但我听说在提供web视图和web应用程序时,最好创建两种操作方法,而不是一种。非常感谢所有发帖的人。
MVC操作-
[HttpPost]
public string CreateResult(Result result)
{
result.ResultDate = DateTime.Now;
repository.InsertResult(result);
repository.Save();
if (result == null)
{
// User entity does not exist in db, return 0
return JsonConvert.SerializeObject(0);
}
else
{
// Success return user
return JsonConvert.SerializeObject(result, Formatting.Indented, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });
}
}
AJAX-
$.ajax({
url: Domain + '/Result/CreateResult',
cache: false,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: '{"Q1":"' + Q1 + '","Q2":"' + Q2 + '","Q3":"' + Q3 + '","Q4":"' + Q4 + '","Q5":"' + Q5 + '","Q6":"' + Q6 + '","Q7":"' + Q7 + '","Q8":"' + Q8 + '","Q9":"' + Q9 + '","Q10":"' + Q10 + '","Total":"' + localStorage.getItem("Total") + '","CaseStudy":"' + localStorage.getItem("CaseStudy") + '","UserId":"' + localStorage.getItem("UserId") + '","Attempts":"' + QnANumAttempts + '"}',
success: function (data) {
try {
if (data != 0) {
//result id used for feedback insertion > update result entity
localStorage.setItem("ResultId", data.ResultId);
viewModel.UserId("You have successfully completed case study " + localStorage.getItem("CaseStudy") + ", please fill out the <a href=evaluation.html target=_self>evaluation.<a/>");
//reset locals
ResetLocalStorage();
//count number of entities for User
CountUserEntitiesInResults();
}
else
{
viewModel.UserId("Your entry has not been saved, please try again.");
}
}catch(error) {
alert("This is the error which might be: "+error.message);
}
},
}).fail(
function (xhr, textStatus, err) {
console.log(xhr.statusText);
console.log(textStatus);
console.log(err);
});
相关文章:
- ngResource没有'从JSON文件解析HTML时不起作用
- Backbone.js 不起作用,而 Underscore、JSON 和 jQuery 可以
- 想要将 JSON 字符串传递给 javascript 变量 [ JSON.parse(),eval()] 对我不起作用,
- 显示 JSON 将不起作用
- Ajax 对 JSON 的请求不起作用
- JSON 数据解析不起作用
- 当图像和链接是 json 对象属性的值时,它们不起作用
- 尝试使用 AngularJS ng-repeat 显示 JSON 数据不起作用
- 对 URL 的 JSON-P 请求不起作用
- ajax get-json函数没有'不起作用
- 将JSON对象转换为敲除observable在IE8中不起作用,但在所有其他浏览器中都起作用
- 从d3.js中的文件读取json数据不起作用
- wordpress phonegap json不起作用
- DatePicker php json 不起作用
- 每个 JSON 不起作用
- 带有 Angular JS 的 JSON 不起作用(Ionic & Cordova)
- 访问json不起作用
- AJAX调用中返回的JSON不起作用
- jQuery's从HTML解析JSON不起作用
- 使用jquery解析json不起作用