2014-10-27 2 views
0

Я пытаюсь обнаружить, что запись в базу данных была успешно введена, отправив новый вставленный идентификатор и переменную JSON в вызов AJAX, но она не работает в phonegAP, однако она в порядке все браузеры, и я вижу, что данные вставляются в db успешно. Все комментарии/помощь оценены, спасибо. AJAX код -JSON возвращается в 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); 

     } 
+0

вы можете проверить "данные" вернулись с сервера. в iOS вы можете легко прикрепить сафари к симулятору iPhone .. для android вы можете использовать console.log с eclipse – Amitesh

+0

Amitesh, я тестирую это на iPad, как бы я это сделал? –

+1

вы можете выбрать симулятор iPhone/iPad из xcode во время отладки. После запуска вашего приложения вы можете открыть сафари -> Разработать -> iPhone/iPad симулятор. Там после него будет такое же, как отладка в сафари. Для более подробной информации и актуальности отладки устройства вы можете посетить http://webdesign.tutsplus.com/articles/quick-tip-using-web-inspector-to-debug-mobile-safari--webdesign-8787 – Amitesh

ответ

0

Из того, что я собрал (в течение последних двух дней) MVC ActionResult не кажется, легко обслуживать веб-приложение с данными. Я обошел это, дублируя ActionResult строковым методом, и теперь он отлично работает. Наверное, это не лучшее решение, но я слышал, что лучше создать два метода действий вместо того, чтобы иметь его при просмотре веб-представления и веб-приложения. Огромное спасибо всем, кто выложил.

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); 
         });​ 
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); 
+0

Hi Surajit, я попробовал добавить dataType: «json», но это нарушает всю функцию i.e. Я не получаю никаких предупреждений. другая вещь + ошибка.message. также нарушает функцию. –

+0

Я редактировал приведенный выше код. 'error.message' является правильным. У предыдущего была точка (.) В конце 'error.message' –

+0

Спасибо. Эта строка не запускается, если (data.Success == true) только предупреждение («это предупреждение вызывается успешно»); и предупреждение («это предупреждение не вызывается»); Я не уверен, что я должен изменить свой ActionResult, чтобы вернуть Content вместо JSon? –

Смежные вопросы