2016-09-18 9 views
0

ログイン(つまり、サーバーに情報を送信)してから、返信用のJSONメッセージを受け取るjavascriptコードがあります。私はこれが最初に投稿を行うことによって実行可能であることを知っていますし、非同期応答では、完了すると、取得します。これには2つのコールバック関数と2つのメッセージが必要です。JavascriptでGETとPOSTを組み合わせることはできますか?

JSONを取得してクエリの一部として送信する方法があるかどうかは疑問だったので、2つではなく1つの要求/応答があります。ここで

は、私が書いたサンプルのポストです:

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を使って返信します。私はjavascriptを表示するために質問を編集し、私はクライアントコードを書く方法を尋ねています。 – 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を避けたいと思います。これはいいですが、私はJavaScriptのレベルでコードが何をしているのか見たいと思っています。リンクありがとう – Dov

関連する問題