gpt4 book ai didi

php - 根据查询字符串替换 HTML?

转载 作者:行者123 更新时间:2023-11-29 18:27:44 25 4
gpt4 key购买 nike

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

我在网上查看了一些资源,但没有任何资源可以在 jsfiddle 中进行测试以正常工作。 Another post here sort of eludes to this .

目标

让一个简单的页面在正文中显示一个 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 以捕获非查询字符串代码, future 可能会出现更多情况。

所以最终的 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 回显,这对我来说就完成了。

最佳答案

这是一个可能对您有帮助的工作示例

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";
}
}

关于php - 根据查询字符串替换 HTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11423726/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com