2017-02-06 32 views
0

如何在HTML5按鈕中插入正確的「xhr」值?使用Javascript和HTML5的XMLHttpRequest

我不知道這整個XMLHttpRequest是如何工作的。我相信這需要:xml數據,文本,數字或HTML5按鈕輸入中的null,並在本例中以文本輸入方式打印出來,但是它可以在其中存儲一個值以稍後調用它。就是那個問題!

<script type="text/javascript"> 
    function readBody(xhr) { 
    var data; 
    if (!xhr.responseType || xhr.responseType === "text"){ 
     data = xhr.responseText; 
    } else if (xhr.responseType === "document") { 
     data = xhr.responseXML; 
    } else { 
     data = xhr.response; 
    } 
    window.document.myform.xhr1.value = data; 
    return data; 
} 
var xhr = new XMLHttpRequest(); 
xhr.onreadystatechange = function() { 
    if (xhr.readyState == 4 && xhr.status == 200); { 
     window.document.myform.readBodyxhr.value = readBody(xhr); 
    } 
    else { 
     alert(xhr.status); 
    } 
    xhr.open('GET', 'http://www.google.com', true); 
    xhr.send(null); 
    } 
</script> 

...HTML5 
<input type="button" name="XMLHttpRequest" value="XMLHttpRequest" onclick="readBody(xhr)" /> 
<input type="text" name="xhr1" value="" size="4"/></td> 
<input type="text" name="readBodyxhr" value="" size="4"/></td>  
+0

'''預計到.value'是字符串,而不是一個'document','ArrayBuffer'或'Blob'。什麼是預期的迴應? – guest271314

+0

我只是希望能夠將xhr添加爲字符串,數字或其他。 「function readBody(xhr){」。您如何在HTML5代碼中添加「xhr」? – losopha

回答

0

移動呼叫.open().send()onreadystatechange處理程序。

替代onloadonerror對於onreadystatechange;以下if條件是語法錯誤。還請注意,XMLHttpRequesttrue傳遞在第三個參數.open()load處理程序以異步返回結果。

<script type="text/javascript"> 
 
    var url = "https://gist.githubusercontent.com/guest271314/6a76aa9d2921350c9d53/raw/1864137bfd2eb62705bd0e71175048a28b3253e6/abc.txt"; 
 

 
    function readBody() { 
 

 
    var xhr = new XMLHttpRequest(); 
 
    
 
    xhr.onload = function() { 
 
     window.document.myform 
 
     .readBodyxhr.value = xhr.responseText; 
 
    } 
 

 
    xhr.onerror = function() { 
 
     alert(xhr.status); 
 
    } 
 

 
    xhr.open("GET", url, true); 
 
    xhr.send(null); 
 
    } 
 
</script> 
 

 
...HTML5 
 
<form name="myform"> 
 
    <input type="button" name="XMLHttpRequest" value="XMLHttpRequest" onclick="readBody()" /> 
 
    <input type="text" name="xhr1" value="" size="4" /> 
 
    <input type="text" name="readBodyxhr" value="" size="4" /> 
 
</form>