Javascript 使用多页选择选项标签对mysql中的数据进行排序
我的网站是使用GET方法导航的,这是index.php文件的框架Javascript 使用多页选择选项标签对mysql中的数据进行排序,javascript,php,jquery,html,mysql,Javascript,Php,Jquery,Html,Mysql,我的网站是使用GET方法导航的,这是index.php文件的框架 <?php include ('header.html'); include ('main-content.html'); include ('footer.html'); ?> 在header.html contains下拉菜单中,选择option tag可根据所选城市对信息进行排序,如下所示: <select onchange="sortResult(this.value)">
<?php
include ('header.html');
include ('main-content.html');
include ('footer.html');
?>
在header.html contains下拉菜单中,选择option tag可根据所选城市对信息进行排序,如下所示:
<select onchange="sortResult(this.value)">
<option value="">Please select city</option>
<option value="City 1">City 1</option>
<option value="City 2">City 2</option>
<option value="City 3">City 3</option>
</select>
下面是标题中的JS函数:
<script>
function sortResult(str)
{
if (str=="")
{
document.getElementById("result").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("result").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","main-content-city.php?q="+str,true);
xmlhttp.send();
}
</script>
以下是我的main-content.html:
<div id="result">
Content displayed here
</div>
此代码正在运行,但它仅适用于main-content.html页面。如果我导航到另一个页面,比如child-content.html,它将无法工作。我应该如何修改JS代码以适应这种情况
这是我的child-content.html页面:
<div id="result">
Content displayed here
</div>
您需要在child-content.html的主体中添加
在Javascript的第6行,您有以下内容
document.getElementByIdresult.innerHTML=
正在查找具有ID结果的元素。如果您的页面上没有这些元素中的一个,那么代码将无法工作请确保DOM元素ID结果出现在child-content.html页面中另一个页面上有什么不同?我们不知道。您是否在console中检查了错误?main-content.html和子内容具有不同的信息,但数据可以按城市排序。所以应用这个JS只对一个页面有效。我想我需要在当前的JS中添加一些条件或代码,但是,无论如何我都找不到使其工作的方法。如果其他页面位于不同的目录级别,您的ajax路径将无效。这就是问题所在吗?路径没有问题。但是这行代码是:xmlhttp.openGET,/main content city.php?q=+str,true;xmlhttp.send;这基本上说明main-content.html的id=result中的内容将被main-content-city.php中的内容替换。如果我导航到chid-content.html页面,上面的代码将不起作用。请在浏览器控制台的“网络”选项卡中检查请求,并确保目标元素也存在,这部分内容是xmlhttp.openGET,main content city.php?q=+str,true;xmlhttp.send;仅适用于main-content-city.php。那么child content city.php呢?@GiangNguyen您正在使用一个相对URL作为AJAX请求。main-content.html和child-content.html是否在同一级别加载?您可能需要将AJAX请求更改为xmlhttp.openGET,/main content city.php?q=+str,true;xmlhttp.send;是的,为了测试的目的,我把它们放在同一个级别。你在child-content.html上有什么收获吗?main-content-city.php将在main-content.html中被替换。child-content.html中将替换child-content-city.php。我是否也需要将这些行添加到js中,这样它将是:xmlhttp.openGET,/child content city.php?q=+str,true;xmlhttp.send;openGET,/main content city.php?q=+str,true;xmlhttp.send???我确实为我的子内容页设置了id=result。但是,这行javascript代码是:xmlhttp.openGET,main content city.php?q=+str,true;xmlhttp.send;仅适用于main-content-city.php页面。child-content-city.php页面如何?请求可能会被缓存,请尝试xmlhttp.openGET,main-content-city.php?q=+str+&+new-Date.getTime,true;xmlhttp.send;