【问题标题】:XMLHttpRequest with Javascript and HTML5带有 Javascript 和 HTML5 的 XMLHttpRequest
【发布时间】:2017-02-06 14:39:03
【问题描述】:

如何将正确的“xhr”值插入 HTML5 按钮?

我不确定整个 XMLHttpRequest 是如何工作的。我相信它需要:来自 HTML5 按钮输入的 xml 数据、文本、数字或 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>      

【问题讨论】:

  • &lt;input type="text"&gt; 期望 .value 是一个字符串,而不是 documentArrayBufferBlob。预期的反应是什么?
  • 我只是希望能够将 xhr 添加为字符串、数字或其他内容。 "function readBody(xhr) { " .如何在 HTML5 代码中添加 "xhr"?

标签: javascript html xmlhttprequest


【解决方案1】:

将调用移至.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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-19
    • 2015-01-24
    • 2017-08-23
    • 1970-01-01
    • 1970-01-01
    • 2012-03-10
    • 2013-03-04
    • 1970-01-01
    相关资源
    最近更新 更多