【发布时间】:2013-10-29 17:13:52
【问题描述】:
我有一个包含 2 <select> 的表单,第一个选择会在页面加载时自动填充,而第二个选择会根据第一个选择中选择的选项自动填充。
To accomplish this, whenever the the select's state changes, the selected value in the first would be passed to a seperate page where it is used to populate the 2nd <select>
问题
通过 url 传递的选定值(本例中为 Food & Beverages)被中途截断,导致将不完整的字符串发送到 2nd 的处理页面,导致无法运行。
确定问题的步骤 我已经回显了通过 url 传递的值,并且只得到了“Food”,其余的字符串被切断了。我尝试将字符串值替换为 Food and Beverage,整个过程完美运行,这让我得出结论,字符串被切断是由于 & 符号导致计算机处理字符串的一部分在&符号之后作为另一个值通过 URL 传递。但是,由于我没有将它分配给变量,因此它没有被传递。
问题
有什么方法可以让我在不被切断的情况下传递价值?
代码摘录:
处理页面
<?PHP
include("cxn.inc");
$query=$cxn->prepare("SELECT * FROM `BusinessSubCategory` WHERE `BusinessCategory`=:businesscategory");
$query->bindValue(":businesscategory",$_GET['category']);
$query->execute();
$count=$query->rowCount();
if($count>0)
{
echo"<option id='subcategory' value=''>Please select a SubCategory</option>";
while($result=$query->fetch(PDO::FETCH_ASSOC))
{
$subcategory=$result['BusinessSubCategory'];
echo"<option id=$subcategory value=$subcategory >$subcategory</option>";
}
}
else
{
echo"<option id='subcategory' value=''>Error,fetch query not run. </option>";
}
?>
JQuery 代码
$(document).ready(function(){
$('#BusinessCreateCategory').load('getbusinesscategory.php');
$('#BusinessCreateCategory').change(function(){
var category=$('#BusinessCreateCategory').val();
window.location.href='getbusinesssubcategory.php?category='+category;
});
编辑:尝试 encodeURIComponent,但数据没有被编码,因为我可以从处理 apge 的 url 中看到它在与号处被切断。但是,如果我要手动输入 url 作为字符串然后使用 encodeURIComponent 对其进行编码,它工作得非常好。任何人都可以解释为什么我无法编码 $('#BusinessCreateCategory').val(); ?谢谢!
例如这行得通
var category="Food & Beverages";
var encoded =encodeURIComponent(category);
window.location.href='getbusinesssubcategory.php?category='+encoded;
例如,这不是
var category=$('#BusinessCreateCategory').val();
var encoded= encodeURIComponent(category);
window.location.href='getbusinesssubcategory.php?category='+encoded;
如果有帮助,我试图通过 url 传递的数据是从我的数据库中获取的。
【问题讨论】:
-
您是否尝试过在值上使用 php urlencode? php.net/manual/en/function.urlencode.php
-
我强烈建议您不要使用字符串作为选项值,而是使用自动增量索引,即
id -
@ChristopherMorrissey 为什么建议使用自动递增索引而不是字符串作为选项值?
-
@Ken 更简洁、更快捷,您可以拥有两个名称相同但父类别不同的子类别,等等。
标签: javascript php jquery html