Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Html 使用XMLHttpRequest读取文本文件?_Html_Xml_Xmlhttprequest - Fatal编程技术网

Html 使用XMLHttpRequest读取文本文件?

Html 使用XMLHttpRequest读取文本文件?,html,xml,xmlhttprequest,Html,Xml,Xmlhttprequest,我一直在尝试使用XMLHttpRequest来读取文本文件并显示文本。文本文件I将被外部链接。到目前为止,我有以下代码 <!DOCTYPE html> <html> <body> <h2>Using the XMLHttpRequest object</h2> <script> <script> var xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", X

我一直在尝试使用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>

使用XMLHttpRequest对象
var xmlhttp=new XMLHttpRequest();
open(“GET”,XMLHttpRequest.txt,true);

我没有看到我的文本文件出现,我完全迷路了。我已经在堆栈溢出上四处寻找答案,但没有找到任何答案。

您还没有指定文本文件的位置

下面是一个使用远程api(不是真正的api端点,只是一个示例url)的工作XMLHttpRequest的示例。您可以将其调整为使用文本文件而不是json。最后记得调用你的函数<代码>金融城(城市)例如

函数查找城市(elem){
设xmlhttp=newxmlhttprequest();
xmlhttp.onreadystatechange=函数(){
if(xmlhttp.readyState==XMLHttpRequest.DONE){
if(xmlhttp.status==200){
document.getElementById(“城市”).value=xmlhttp.responseText;
}
else if(xmlhttp.status==400){
警报(“出现错误400”);
}
否则{
警报(“返回了200以外的内容”);
}
}
};
open(“GET”https://api.example.com/api/postcodes.json?pnr=“+elem.value+”&客户端URL=http://localhost",对),;
xmlhttp.send();

}
我的文本文件位于计算机本地的资产文件夹下。我会做类似于“assets/XMLHttpRequest.txt”的事情吗?不,我认为这行不通。改为使用xmlhttp.open(),如我的示例所示,并使用本地文件而不是url。不确定是否应在文件前使用斜杠,请尝试两种方法(/file.txt或仅使用file.txt)。语法如下:
XMLHttpRequest.open(method,url[,async[,user[,password]])
因此您可以删除
GET,
之后和
之前的所有内容,true
。True表示它是异步加载的。