2016-09-18 36 views
0

我有JavaScript代碼,應登錄(即發送一些信息到服務器),然後收到回覆JSON消息。我知道這是可行的,首先做一個職位,然後在異步響應,當它完成時,做一個get。這需要兩個回調函數和兩個消息。是否可以在Javascript中組合GET和POST?

我只是想知道是否有任何方法來執行get和發送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.responseText在返回時?

+2

在1次調用中這樣做沒有問題。它必須在服務器端進行處理。 –

+0

我認爲服務器通過post(stdin)接收參數並通過stdout回覆。我編輯了問題以顯示javascript,我在問如何編寫客戶端代碼。 – Dov

+0

您只需解析回調函數中的響應。 –

回答

1

如果您正在執行任何登錄功能,則應始終使用HTTP POST方法。

您可以使用AJAX(W3schools documentation about AJAX)來處理通過POST發送登錄表單,然後在同一代碼塊中處理響應。波紋管就是一個例子。

$('#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