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

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

问题描述

Good day。

我从来没有真正感觉到JavaScript,所以这个不寻常和简单的问题。 em>

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?

感谢。

编辑

对不起,我忘了提到:从指定的网址获取页面内容到JS var。

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

以下 Brendan 建议

Following Brendan Suggestion

我已经看过布伦丹替代别处尝试了,但是当时没有工作,它现在不起作用同时Firebug和浏览器测试(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

This is a modified version of an example you can find at 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和status)。结论 - 不要将此函数的输出分配给任何var。而是执行以下操作:

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 */ }

没有,所有人都可以看到是'undefined'...

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

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

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