Javascript 将页面内容加载到变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4229043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:29:08  来源:igfitidea点击:

Load page content to variable

javascriptdombrowser

提问by Fábio Antunes

Good day.

再会。

I never really got a good hand at JavaScript, therefore this unusual and simple question.

我从来没有真正掌握过 JavaScript,因此这是一个不寻常且简单的问题。

How can i load a page content to a JavaScript variable, with the least amount of code, no framework, and the less impact possible on performance?

如何将页面内容加载到 JavaScript 变量中,代码量最少,没有框架,对性能的影响可能更小?

Thanks.

谢谢。



EDIT

编辑

Sorry guys. I forgot to mention: Get the page content from the specified url to a JS var.

对不起大家。忘了说:从指定的url获取页面内容到一个JS var。



Following BrendanSuggestion

遵循布伦丹的建议

I had already seen Brendan alternative elsewhere and tried it, but it didn't work at the time, and it doesn't work now. Meanwhile Firebug and the Browsers tested (IE8 and FF) don't report any error. So whats wrong?

我已经在其他地方看到过 Brendan 替代方案并尝试过,但当时没有用,现在也没有用。同时,Firebug 和经过测试的浏览器(IE8 和 FF)不报告任何错误。那么怎么了?

采纳答案by Brendan

This is a modified version of an example you can find at w3schools.com.

这是您可以在w3schools.com 上找到的示例的修改版本。

<script type="text/javascript">
    function loadXMLDoc(theURL)
    {
        if (window.XMLHttpRequest)
        {// code for IE7+, Firefox, Chrome, Opera, Safari, SeaMonkey
            xmlhttp=new XMLHttpRequest();
        }
        else
        {// code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function()
        {
            if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
                alert(xmlhttp.responseText);
            }
        }
        xmlhttp.open("GET", theURL, false);
        xmlhttp.send();
    }
</script>

So just make "example.html" be any sort of path (relative or absolute) to the page you want to load, and xmlhttp.responseTextwill be a string containing the response content. You can also use xmlhttp.responseXMLif you want it to be stored as a traversable XML document. Anyway, just assign either of those to a variable of your choice, and you will have it!

因此,只需将“example.html”设为您要加载的页面的任何类型的路径(相对或绝对),并且xmlhttp.responseText将是包含响应内容的字符串。xmlhttp.responseXML如果您希望将其存储为可遍历的 XML 文档,也可以使用。无论如何,只需将其中任何一个分配给您选择的变量,您就会拥有它!

Note that 'loadXMLDoc' does not return anything directly but defines one of its members ('onreadystatechange') to do that job, and to does it only in certain condition (readyState and status). Conclusion - do not assign the output of this function to any var. Rather do something like:

请注意,'loadXMLDoc' 不直接返回任何内容,而是定义其成员之一 ('onreadystatechange') 来执行该工作,并且仅在特定条件下(readyState 和状态)执行此操作。结论 - 不要将此函数的输出分配给任何变量。而是做类似的事情:

var xmlhttp=false;
loadXMLDoc('http://myhost/mycontent.htmlpart');
if(xmlhttp==false){ /* set timeout or alert() */ }
else { /* assign `xmlhttp.responseText` to some var */ }

Without that, all one can see is 'undefined'...

没有它,人们只能看到“未定义”......

回答by wajiw

To get everything inside the html tags:

要获取 html 标签内的所有内容:

var html = document.getElementsByTagName('html')[0];
var text = html.innerHTML;

Then you can wrap that in html tags. Doesn't capture doctype or anything else you'd have outside the html tags, but it's a quick way to grab most of the content.

然后您可以将其包装在 html 标签中。不会捕获 doctype 或 html 标签之外的任何其他内容,但这是获取大部分内容的快速方法。

回答by Just Lucky Really

I know this question is really old now, but I have had the same issue with trying to get the page contents into a variable, but have finally figured out a way in Javascript :D (With some help from the internet ...)

我知道这个问题现在真的很老了,但是我在尝试将页面内容放入变量时遇到了同样的问题,但终于在 Javascript 中找到了一种方法:D(在互联网的帮助下......)

So here it goes ...

所以在这里......

I made a function with a callback to get a desired page:

我做了一个带有回调的函数来获得所需的页面:

function getPageContents(callback,url,params) {
    http=new XMLHttpRequest();
    if(params!=null) {
        http.open("POST", url, true);
        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    } else {
        http.open("GET", url, true);
    }
    http.onreadystatechange = function() {
        if(http.readyState == 4 && http.status == 200) {
            callback(http.responseText);
        }
    }
    http.send(params);
}

Note that I have made it in such a way, that it wont accept GET paramaters. This is intentional, as I have no need to use GET for my application. If params are set, these will be sent as POST.

请注意,我已经这样做了,它不会接受 GET 参数。这是故意的,因为我不需要为我的应用程序使用 GET。如果设置了 params,这些将作为 POST 发送。

Then to use the function, lets say I want to post a name to findpersoninfo.phpwhich will output a JSON array of that persons info, I can do this:

然后要使用该函数,假设我想发布一个名称,findpersoninfo.php该名称将输出该人员信息的 JSON 数组,我可以这样做:

getPageContents(function(result) {
    personinfo=JSON.parse(result);
    //Now I can do anything here with the personinfo array
},'http://localhost/findpersoniinfo.php','fname=stretch&lname=wright')

Taking it a step further, you can nest this inside another function, lets call it getPersonInfo():

更进一步,您可以将它嵌套在另一个函数中,让我们调用它getPersonInfo()

function getPersonInfo(fname,lname) {
    getPageContents(function(result) {
        personinfo=JSON.parse(result);
        //Now I can do anything here with the personinfo array
    },'http://localhost/findpersoninfo.php','fname='+fname+'&lname='+lname)
}

Of course, my knowledge of Javascript is still in it's infancy, and welcome any constructive feedback :D

当然,我对 Javascript 的了解还处于起步阶段,欢迎任何建设性的反馈 :D

回答by asmaier

A simple solution to download JSON data from a url like /v1/data?format=json:

从如下网址下载 JSON 数据的简单解决方案/v1/data?format=json

xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET", "/v1/data?format=json", false);
xmlhttp.send();
var data = JSON.parse(xmlhttp.responseText);