2012-02-17 3 views
1

나는 아약스 요청을하는 곳이 2 가지 기본적인 테스트 어플리케이션을 가지고있다. 처음에는 Ajax 요청을 호출 한 후 값을 검색하기 전에 ajax data.responseText을 구문 분석해야합니다. 두 번째 경우에는 에 직접 액세스 할 수 있습니다.. 첫 번째 응용 프로그램의가끔은 왜 내가 parseJSON을하고 가끔 ajax 요청을 할 때가 아니 었나요?

코드 : 당신이 볼 수 있듯이

@using (Ajax.BeginForm("JsonAdd", "People", new AjaxOptions { OnComplete = "JsonAdd_OnComplete" })) 
{ 
... 
} 

function JsonAdd_OnComplete(data) { 

    var json = $.parseJSON(data.responseText); 

    if (json.Success) { 
     $("#PersonList").html(json.PartialViewHtml); 
    } 

    $("#addPersonModal").slideToggle(); 
    $("#message").html(json.Message); 
} 

, 나는 값을 얻기 전에 먼저 data.responseText을 구문 분석 할 필요가있다. 내가 직접 액세스 값을 CAS,이 들어

@using (Ajax.BeginForm("_NewPersonToKeepInformed", "General", new { id = "NewPersonToKeepInformed" }, new AjaxOptions { Confirm = "Are you sure ?", HttpMethod = "POST", OnSuccess = "AddedSuccess" })) 

function AddedSuccess(response) { 
    alert(response.message); 
} 

:

다음은 두 번째 응용 프로그램입니다.

업데이트 여기

내 컨트롤러 액션 방법 :

public JsonResult _NewPersonToKeepInformed(NewPersonToKeepInformedViewModel viewModel) 
    { 
     ... 
     // return newly added person in a Json object 
     return Json(new { message = "Ajout effectué", firstName = viewModel.FirstName, lastName = viewModel.LastName, phone = viewModel.Phone, mail = viewModel.Mail }); 
    } 

이유는 다음과 같습니다

public JsonResult JsonAdd(AddPersonViewModel AddPersonModel) 
    { 
     ... 
     return Json(new 
     { 
      Success = true, 
      Message = "The person has been added!" 
     }); 
    } 

번째 하나?

감사합니다.

+0

그'@ using' 구문은 무엇입니까? 'Ajax' 객체는 어디서 오는가? –

+0

이것은 ASP.NET MVC 구문의 것입니다. Ajax 객체가 거기에서오고있다. – Bronzato

+0

return Json (새 { 성공 = true, 메시지 = "이 사람이 추가되었습니다!" }); – Bronzato

답변

6

첫 번째 경우에는 OnComplete을 사용하고 두 번째 경우에는 OnSuccess을 사용합니다. 그것이 차이점입니다. jQuery의 completesuccess 콜백에 해당합니다. jQuery는 complete 콜백 내의 Content-Type 헤더를 기반으로 서버의 응답을 구문 분석하지 않습니다. 그래서 수동으로 파싱해야합니다. success 콜백에서 이것은 자동으로 수행됩니다. 그래서 당신이 첫 번째 작업을 위해 이것을 사용하기를 원하면 new AjaxOptions { OnComplete = "JsonAdd_OnComplete" }new AjaxOptions { OnSuccess = "JsonAdd_OnComplete" }으로 바꿉니다.

+0

고맙습니다. – Bronzato

관련 문제