为了理解处理查询字符串,我一直在查看此SO Post。很高兴看到所有的回复。我想要了解的是,如何更进一步,提供的查询字符串实际上替换DOM中的对象,如特定的DIV,并将其替换为另一个DIV(可以隐藏在门外),或者只是替换DIV中的内容。
我在网上看过一些资源,但是我没有任何东西可以在jsfiddle中测试,以便正常工作。 Another post here sort of eludes to this
目标
有一个简单的页面显示正文中的单个DIV。 加载页面时,将显示DIV和内容。 当使用?q = what加载页面时,该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回显即可显示或隐藏,这样就可以了。
答案 0 :(得分:3)
这是一个可以帮助您的工作示例
有关详细信息,请参阅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";
}
}
答案 1 :(得分:1)
如何在jQuery中执行此操作。
以下说明如何替换innerHTML。
How to replace innerHTML of a div using jQuery?
这个问题解释了如何从当前URL获取参数值。
最后,您还可以通过Ajax,更具体地说是jQuery.ajax()方法从数据库中获取数据(例如,创建动态页面)。