javascript - AJAX 调用中返回的 JSON 不起作用

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

        }

最佳答案

发现代码有两个问题:

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

关于javascript - AJAX 调用中返回的 JSON 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26586743/

相关文章:

javascript - jquery 输入字段模式

jquery - 简单的 jquery 下拉菜单 -clearTimeout、setTimeout 问题

javascript - 锁定正文滚动时滚动 Div。溢出:Hidden?

javascript - onbeforeunload 在 Safari 或 Chrome 中似乎不起作用

javascript - 尝试更改 Textarea 的值(使用 Skulpt)

javascript - 从异步或同步 JavaScript 请求返回值

javascript - 在 moment.js 中设置浏览器语言

javascript - jquery ajax post 中的 While 循环

jquery:如何转义字符串?

javascript - Ajax 在下拉列表中包含数据