2017-07-14 54 views
0

我試圖將alert(allText);的內容記錄到另一臺服務器上,例如www.otherwebsite/logger?log = allText(),而不是alert msg,這是當前彈出的內容。如何使用XMLHttpRequest()將內容轉發到日誌服務器?

換句話說,我如何使用XMLHttpRequest產生另一個請求到日誌服務器,信息爲allText

我目前使用這個腳本加載的內容,但我不知道如何與allText

<script> 
    function readTextFile(file) 
    { 
     var rawFile = new XMLHttpRequest(); 
     rawFile.open("GET", file, false); 
     rawFile.onreadystatechange = function() 
     { 
      if(rawFile.readyState === 4) 
      { 
       if(rawFile.status === 200 || rawFile.status == 0) 
       { 
        var allText = rawFile.responseText; 
        alert(allText); 
       } 
      } 
     } 
     rawFile.send(null); 
    } 

    readTextFile("http://null.jsbin.com/runner"); 

</script> 

爲了測試,我跑與jsbin腳本生成另一個請求到我的日誌服務器。 com

任何意見和建議將不勝感激。

回答

1

使嵌套後調用API來要發佈的數據:

<script> 
    function readTextFile(file) 
    { 
     var rawFile = new XMLHttpRequest(); 
     rawFile.open("GET", file, false); 
     rawFile.onreadystatechange = function() 
     { 
      if(rawFile.readyState === 4) 
      { 
       if(rawFile.status === 200 || rawFile.status == 0) 
       { 
        var allText = rawFile.responseText; 
        var xhr = new XMLHttpRequest(); 
        xhr.open("POST", '/server', true); 

        //Send the proper header information along with the request 
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 

        xhr.onreadystatechange = function() { 
        //Call a function when the state changes. 
         if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) { 
         // Request finished. Do processing here. 
         } 
        } 
        xhr.send(allText); 
       } 
      } 
     } 
     rawFile.send(null); 
    } 

    readTextFile("http://null.jsbin.com/runner"); 

</script> 
+0

感謝。這是我正在尋找的。使用POST更好。 – pancho

相關問題