简体   繁体   English

在javascript中包含基于url的内容?

[英]Include content based on url with javascript?

I would like to include content based on url with javascript. 我想使用javascript包含基于URL的内容。 For example, if the url is: 例如,如果URL为:

http://foo.com/test

then include the following content from somefile.html. 然后从somefile.html中包含以下内容。 Can this be done in javascript? 可以用javascript完成吗? If so, how? 如果是这样,怎么办? I don't want to use an iframe. 我不想使用iframe。

Sorry to bump an old thread but I've just been working on this - Pleasestand's answer didn't work for me so I made a few adjustments and now it works perfectly. 抱歉,碰到了旧的线程,但我一直在努力解决这个问题-Pleasestand的答案对我没有用,所以我做了一些调整,现在可以正常使用了。

$(function() {
    if(window.location.href.indexOf('/yourURL/')!==-1) {
        $('#containerdiv').load('/your.php');
    }
});

PHP is really the better tool to use for this. PHP确实是用于此目的的更好工具。 However, if you cannot use PHP or another server-side scripting language such as Perl, Python, VBScript, or C#, you could use the .load() method of the jQuery JavaScript Library combined with code to check the URL using window.location , for example: 但是,如果您不能使用PHP或其他服务器端脚本语言(例如Perl,Python,VBScript或C#),则可以将jQuery JavaScript库.load()方法与代码结合使用,以使用window.location检查URL。 , 例如:

$(function() {
    if(window.location.pathname == '/test') {
        $('#idOfContainer').load('/somefile.html');
    }
});

For more complex cases, you could use regex . 对于更复杂的情况,可以使用regex

Well, JavaScript gets run on the client, so you can't exactly decide to show a different page. 嗯,JavaScript已在客户端上运行,因此您不能完全决定显示其他页面。 If you want to do serverside redirects, you will have to write some serverside code or configure your web server to redirect. 如果要进行服务器端重定向,则必须编写一些服务器端代码或将Web服务器配置为重定向。

However, if you are on the page, you can figure out what page you are on, and execute some clientside code. 但是,如果您在页面上,则可以找出您所在的页面,并执行一些客户端代码。

You can get the current location like this: 您可以像这样获取当前位置:

window.location.href

So you can write something like: 因此,您可以编写如下内容:

if(window.location.href.indexOf('http://foo.com/test') >= 0) {
    window.location.href = 'http://foo.com/somefile.html';
} // <-- redirect to http://foo.com/somefile.html

Or you can write an iframe into the page pointed at your 'somefile.html'. 或者,您也可以将iframe写入指向“ somefile.html”的页面。

You can include content using AJAX http://en.wikipedia.org/wiki/XMLHttpRequest . 您可以使用AJAX http://en.wikipedia.org/wiki/XMLHttpRequest包含内容。 You can check the URL with the location object https://developer.mozilla.org/en/window.location 您可以使用位置对象https://developer.mozilla.org/en/window.location检查URL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM