2016-08-25 3 views
1

post 요청 중에 오류를 catch하는 방법 javascript? 나는 readyState == 4 요청이 완료되었다는 것을 의미하고, status==200이 요청이 성공했다는 것을 의미하는지를 안다. 게시물 요청이 실패 할 때 인터넷 연결이 실패하거나 잘못된 값이되었다는 메시지가 표시됩니다.자바 스크립트 게시/요청 읽기 캐치 오류

현재이 같은 일이, 모달 괜찮 작동하고있을 때의

var xhttp = new XMLHttpRequest(); 
    xhttp.open("POST", url, true); 
    xhttp.setRequestHeader("Content-type", "application/json"); 
    xhttp.onreadystatechange = function() { 
     if (xhttp.readyState == 4 && xhttp.status == 200) { 
      // document.getElementById("demo").innerHTML = xhttp.responseText; 
      hideToolbar(); 
      console.log('Saving successful.'); 
     } else if(xhttp.status == "failed"){ 
      console.log('Sorry there is a problem.'); 
     } 
    }; 
    var data = JSON.stringify({ 
     "name":"name", 
     "definition":diagramData 
    }); 
    xhttp.send(data); 
+0

당신은 오류 처리에 대한 다른 상태 코드와 readystates를 확인, 또는 [Ajax 요청이 자바 스크립트에 실패했다 경우 검지]의 try/catch 블록 –

+1

가능한 복제를 실행할 수 있습니다 (http://stackoverflow.com/questions/22925803/detect-if-ajax-request-had-failed-in-javascript) –

+0

'.onload'를 듣고 있다면 readyState – maioman

답변

0

응답이 도착하면 그래서 이것은 단지 트리거 우선 해제, 당신은 xhttp.onreadystatechange = function(...이 포장 할 것입니다. 어쩌면 코드의 중간에 코드를 잘라내도되지만, 언급하는 것이 좋습니다.

둘째, 200이 아닌 상태에서 실패 할 경우 캐치 올을 수행하는 것이 일반적으로 좋지 않습니다. 때때로 서버가 201,202를 보내고 여전히 정상적으로 작동 할 수 있습니다. else 문을 else if으로 변경하고 오류 메시지가 if(xhttp.status >= 400)인지 명시 적으로 확인하십시오.

그러나 '그냥 jQuery를 사용하십시오.'라는 사람은 싫지만 이미 사용하고 있습니다. jQuery는 AJAX 호출을 크게 단순화하고 심지어 결과에 대한 내장 된 약속을 제공합니다. 이 같은 위를 달성 할 수 :

$.post('http://my-url.com', {my: 'data'}).done(function(response) { 
    hideToolbar(); 
    $("#myModal").modal(); 
    }) 
    .error(function(error) { 
    console.log('did not work because of', error)}); 
+0

$ ("# modal")은 사용하지 않으므로이 요청에 대해 바닐라 js에 머물고 싶습니다. – nCore