2016-09-18 6 views
0

로그인 (즉, 서버에 일부 정보 보내기) 자바 스크립트 코드가 있고 회신 JSON 메시지가 나타납니다. 나는 이것이 게시물을 먼저 수행함으로써 가능하다는 것을 알고있다. 그리고 비동기 응답에서, 그것이 완료되면 get을한다. 이렇게하려면 두 가지 콜백 함수와 두 개의 메시지가 필요합니다.Javascript에서 GET과 POST를 결합 할 수 있습니까?

JSON을 쿼리의 일부로 보내고 보낼 수있는 방법이 있는지 궁금해서 그냥 두 개가 아닌 하나의 요청/응답이 있도록했습니다.

function post(url, payload, callback) { 
    payload = JSON.stringify(payload); 
    var http = new XMLHttpRequest(); 
    http.open("POST", location.pathname + url, true); 

    http.setRequestHeader("Content-type", "application/json"); 

    http.onreadystatechange = function() { 
    if (http.readyState === 4 && http.status !== 200) { 
     callback(false, http.response); 
    } else if (http.readyState === 4 && http.status === 200) { 
     callback(true, http.response); 
    } 
    return; 
    }; 

    http.send(payload); 
} 

내가 JSON을 다시 얻고 싶은 경우에, 나는 무엇을해야합니까 : 여기

은 내가 쓴 샘플 게시물입니다?

POST를 GET으로 변경하고보고있는 것처럼 간단합니까? http.response 반환시의 텍스트?

+2

1 통화에서 아무런 문제가 없습니다. 서버 측에서 처리해야합니다. –

+0

나는 서버가 post (stdin)를 통해 매개 변수를 받고 stdout을 통해 응답한다. 내가 자바 스크립트를 표시하는 질문을 편집, 나는 클라이언트 코드를 작성하는 방법을 묻습니다. – Dov

+0

콜백 함수에서 응답을 구문 분석하면됩니다. –

답변

1

로그인 기능을 수행하는 경우 항상 HTTP POST 메소드를 사용해야합니다.

POST를 통해 로그인 양식을 처리 한 다음 동일한 코드 블록에서 응답을 처리하는 데 AJAX (W3schools documentation about AJAX)를 사용할 수 있습니다. 벨로우즈가 그 예입니다.

$('#login-form').submit(function(e) { 
    e.preventDefault(); // Prevents the page from refreshing 
    // serializes the form data with id login-form 
    var formData = $(this).serialize(); 
    $.ajax({ 
     type: 'POST', 
     data: formData, 
     contentType: 'application/x-www-form-urlencoded', 
     dataType: 'json', 
     url: $(this).attr('action'), 

     //if your server sends a status OK message handle the response 
     //data will be the JSON response from the server 

     success: function(result,status,xhr) { 
      var jsonRes = JSON.parse(result); // parse the JSON object 
      console.log(jsonRes); 
     }, 

     //if there was an error with your request the server will send 
     // an error response code and it is handled here 
     error: function(xhr,status,error) { 
      console.log(error); 
     } 
    }); 
+0

jQuery를 특별히 피하고 싶습니다. 이것은 좋은 일이지만, 나는 자바 스크립트 레벨에서 코드가 무엇을하는지보고 싶다. 링크 주셔서 감사합니다. – Dov

관련 문제