使用 XMLHttpRequest 读取文本文件?

匿名的

我一直在尝试使用 XMLHttpRequest 来读取文本文件并显示文本。文本文件 I 将被外部链接。到目前为止,我有以下代码

<!DOCTYPE html>
<html>
<body>

<h2>Using the XMLHttpRequest object</h2>

<script>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", XMLHttpRequest.txt, true);
</script>
</script>

</body>
</html>

我没有看到我的文本文件出现,我完全迷路了。我已经环顾堆栈溢出寻找答案,但没有找到任何东西。

阿纳托希曼

您尚未指定文本文件所在的位置。

这是一个带有远程 api(不是真正的 api 端点,只是一个示例 url)的工作 XMLHttpRequest 的示例。您可以将其调整为使用文本文件而不是 json。最后记得调用你的函数!findCity( city )例如。

function findCity(elem) {

        let xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
          if (xmlhttp.readyState == XMLHttpRequest.DONE) {
             if (xmlhttp.status == 200) {
                 document.getElementById("city").value = xmlhttp.responseText;
             }
             else if (xmlhttp.status == 400) {
                alert('There was an error 400');
             }
             else {
                 alert('something else other than 200 was returned');
             }
          }
      };

    xmlhttp.open("GET", "https://api.example.com/api/postcodes.json?pnr=" + elem.value + '&clientUrl=http://localhost', true);
      xmlhttp.send();
  }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章