如何写一个JavaScript返回网页的内容作为结果,当URL给出

How to write a JavaScript which returns the contents of a webpage as result when the URL is given

本文关键字:结果 给出 URL 何写一 JavaScript 返回 网页      更新时间:2023-09-26

我想写一个JavaScript返回一个网页的内容时给出URL和输入这些内容作为表中的数据?

提示框不工作

返回HTML内容作为字符串,给定URL。JavaScript函数返回一个空白屏幕。

下面是我的代码:
<html>
<head></head>
<body>
<script type="text/JavaScript"> function httpGet(theUrl) {
    var xmlHttp = null;
    xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", theUrl, false);
    xmlHttp.send(null);
    return xmlHttp.responseText;
}
document.write(httpGet("stackoverflow.com/")); </script>
</body>
</html>

你可以简单地通过使用javascript的ajax获取网页的内容

var contents="";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    contents=this.responseText;
  }
};
xhttp.open("GET", "webpage.html", true);
xhttp.send();

虽然您也可以操作HTML,但您应该确保webpage.html以有效的格式显示数据,以便您轻松操作。如JSON, xml或其他任何东西,以便您可以使用contents变量中的数据,并在插入语句中遍历它。

显示黑屏的原因是由于交叉原点策略。stackoverflow.com不允许CORS(跨源请求)。

还有一件事,除非你是从一个相对Url请求,否则用协议名指定地址。

Like : 'stackoverflow.com' to 'http://stackoverflow.com'

所以只要改变地址到你的文件,它会工作得很好。:)