基于查询字符串替换HTML

Replace HTML based on query string?

本文关键字:字符串 替换 HTML 查询 于查询      更新时间:2023-09-26

我一直在看这篇SO Post,以了解处理查询字符串的过程。很高兴看到所有的回复。我试图理解的是,如何更进一步,提供的查询字符串实际替换DOM中的对象,例如特定的DIV,并用另一个DIV(可能隐藏在门外)替换它,或者只是替换DIV中的内容。

我在网上看过一些资源,但没有什么可以在jsfiddle中进行测试以正常工作。这里的另一个帖子有点回避了这一点。

目标

让一个简单的页面在正文中显示一个DIV。加载页面时,会显示DIV和内容。使用加载页面时?q=不管怎样,该DIV内的内容被替换为其他内容。

我的解决方案

为了有一个DIV dissapea,这是第一个需要解决的问题,基于一个查询字符串,我在我的页面上实现了这个:

if (strrpos($_SERVER['REQUEST_URI'], '/landingpage/index.php?q=1') === strlen($_SERVER['REQUEST_URI']) - strlen('/landingpage/index.php?q=1')) {
    $style = "display: none";
}
else {
    $style = "display: inline";
}

然后我把它放在我的DIV中:

<div id="theForm" style="<?php echo $style; ?>">
    //Form code here
</div>

这让我至少在查询字符串存在的情况下清除了DIV。

下一步,不是真正清除它,而是用一些内容替换它。

我在原始PHP中添加了以下内容:

$thankYou = "<h1>Thank You for signing up</h1>";

在第一个if下,并将else更改为elseif以捕获非查询字符串代码,可能还会出现更多情况。

所以最后的PHP代码看起来是这样的:

if (strrpos($_SERVER['REQUEST_URI'], '/landingpage/index.php?q=1') === strlen($_SERVER['REQUEST_URI']) - strlen('/landingpage/index.php?q=1')) {
    $style = "display: none";
    $thankYou = "<h1>Thank You for signing up</h1>";
}
elseif (strrpos($_SERVER['REQUEST_URI'], '/landingpage/index.php') === strlen($_SERVER['REQUEST_URI']) - strlen('/landingpage/index.php')) {
    $style = "display: inline";
    $thankYou = "";
}

然后,只需要在即将显示或隐藏的DIV之前添加$thankYou变量的PHP echo,这对我来说就完成了

下面是一个可以帮助的工作示例

http://www.fridgefilters.com/refrigerator-ice-and-water-filter-ukf8001.html?cust-title=欢迎+堆栈+溢出

有关的详细信息,请参阅JavaScript

在主页上:

<script>writeCustomHeader('cust-title','customHeader')</script>

在附加文件mss.js:中

function returnQueryValue(match) {
    var query = location.search.substr(1);
    var pairs = query.split("&");
    for(i=0;i<pairs.length;i++){
        var name = pairs[i].split("=")[0];
        var val = pairs[i].split("=")[1];
        if(name==match){
            val = unescape(val.replace(/'+/g, " "));
            return val;
        }
    }
}
function writeCustomHeader(match,id) {
    var newHeader=returnQueryValue(match);
    if(!newHeader)return;
    var id = document.getElementById(id);
    var h1 = document.getElementsByTagName('h1')[0];
    if(newHeader.length>0 && id && id!='undefined'){
        id.innerHTML=newHeader
        h1.className=h1.className+" small";
        document.getElementById('customHeader').className="block";
    }
}

如何在jQuery中做到这一点。

下面介绍如何替换innerHTML。

如何使用jQuery替换div的innerHTML?

这个问题解释了如何从当前URL中获取参数值。

获取转义URL参数

最后,您还可以通过Ajax,特别是jQuery.Ajax()方法,从数据库中获取数据(例如创建动态页面)。

http://api.jquery.com/jQuery.ajax/