2

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

我在网络上查看了一些资源,但没有什么可以在 jsfiddle 中进行测试以正常工作。此处的另一篇文章对此有所回避

目标

有一个简单的页面在正文中显示一个 DIV。加载页面时,会显示 DIV 和内容。使用 ?q=whatever 加载页面时,该 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 回显,这对我来说就是这样。

4

2 回答 2

3

这是一个可以帮助您的工作示例

http://www.fridgefilters.com/refrigerator-ice-and-water-filter-ukf8001.html?cust-title=welcome+stack+overflow

有关详细信息,请参阅 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";
    }
}
于 2012-07-11T00:04:46.790 回答
1

如何在 jQuery 中做到这一点。

下面解释如何替换innerHTML。

如何使用 jQuery 替换 div 的 innerHTML?

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

获取转义的 URL 参数

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

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

于 2012-07-11T00:13:45.173 回答