简体   繁体   中英

XMLHttpRequest with Javascript and HTML5

How do you insert the correct "xhr" value into the HTML5 button?

I am not sure how this whole XMLHttpRequest works. I believe it takes: xml data, text, numbers or null from the HTML5 button input and prints it out in text input in this case but can it store a value in it to call on it later. That is the question!

<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>      

Move call to .open() and .send() outside of onreadystatechange handler.

Substituted onload and onerror for onreadystatechange . ; following if condition is a syntax error. Note also, XMLHttpRequest with true passed at third parameter at .open() sets load handler to return results asynchronously.

 <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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM