加载页面内容变量 [英] Load page content to variable

查看:118
本文介绍了加载页面内容变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

美好的一天。

我从来没有真正在JavaScript的拿到一手好牌,所以这个不寻常的和简单的问题。

我如何可以加载一个网页内容到一个JavaScript变量,用code,无框架量最少,而且对性能的影响较小可能吗?

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?

感谢。

修改

对不起球员。我忘了提及:获取从指定的URL页面内容以一个JS变种

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

<一个href=\"http://stackoverflow.com/questions/4229043/load-page-content-to-variable/4229141#4229141\">Suggestion

Following Brendan Suggestion

我已经看到布兰登替代其他地方尝试过,但它并没有在工作的时候,它现在无法正常工作。同时萤火虫和测试的浏览器(IE8和FF)不报告任何错误。所以,什么是错?

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?

推荐答案

这是你能找到的 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>

因此​​,只要example.html的是任何类型的路径(相对或绝对)到要加载的页面,而 xmlhttp.responseText 将是一个字符串包含响应的内容。如果你希望它被存储为一个遍历XML文档,你也可以使用 xmlhttp.responseXML 。总之,只要分配任意那些您所选择的变量,你会有的!

So just make "example.html" be any sort of path (relative or absolute) to the page you want to load, and xmlhttp.responseText will be a string containing the response content. You can also use xmlhttp.responseXML if 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!

请注意,loadXMLDoc'并不直接返回什么,但确定其成员之一('的onreadystatechange')这样做的工作,并不会只在一定条件下(readyState的和状态)。结论 - 此函数的输出不分配给任何变种。而这样做:

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:

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'...

这篇关于加载页面内容变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆