在AJAX调用中返回的JSON无效

时间:2014-10-27 11:39:06

标签: javascript jquery ajax json cordova

我试图通过将新插入的ID和JSON变量发送到AJAX调用来检测已成功输入数据库条目但是它在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);

        }

2 个答案:

答案 0 :(得分:1)

发现代码有两个问题:

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);

答案 1 :(得分:0)

根据我收集的内容(过去两天),MVC ActionResult似乎无法轻松地为数据提供webapp。我通过使用字符串方法复制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);
                         });​