如何通过jQuery Load传递两个或更多变量

时间:2014-01-21 00:44:37

标签: javascript php jquery

我从这里获得了世界数据库:https://code.google.com/p/worlddb/

我已经设置了数据库并使用php,mysql和jquery我正在尝试生成三级选择下拉列表以从区域和国家/地区生成城市列表。

我正在做的是选择通过包含区域的jquery加载外部文件的国家/地区下拉列表。然后选择区域,通过jquery触发另一个外部负载来填充城市。

$(document).ready(function() {
// get states names based on country drop down
$("#ddCountry").change(function() {
$("#ddStates").load("includes/getStates.php?choice2=" + $("#ddCountry").val());
$("#ddCountryCode").load("includes/getCountryCode.php?choice1=" + $("#ddCountry").val());
});
// get city name for specific state
$("#ddStates").change(function() {
$("#ddCity").load("includes/getCities.php?choice3=" + $("#ddStates").val());
});
});

这很好用。问题是cities表需要两个参数来从一个区域加载城市。一个是区域代码,另一个是国家代码。当我在与$ choice1相同的页面选择国家/地区时,我填写了国家/地区代码。

我需要这部分

$("#ddStates").load("includes/getStates.php?choice2=" + $("#ddCountry").val());

传递两个变量而不是一个。目前它传递的单个变量#ddCountry值。我需要传递更多的值,即#ddCountryCodeGot,它被作为id #ddCountryCode中的输入值被检索。

如何将两个变量传递到通过此行调用城市的页面

$("#ddStates").load("includes/getStates.php?choice2=" + $("#ddCountry").val());

如果我这样做:

$("#ddStates").load("includes/getStates.php?choice2=" + $("#ddCountry").val()&choice4=" + $("#ddCountryCodeGot").val());

它会触发错误。 提前谢谢。

从以下答案中得到解决方案:这里有更新的正确代码正在运行。

$(document).ready(function() {
// get states names based on country drop down
$("#ddCountry").change(function() {
$("#ddStates").load("includes/getStates.php?choice2=" + $("#ddCountry").val());
$("#ddCountryCode").load("includes/getCountryCode.php?choice1=" + $("#ddCountry").val());
});
// get city name for specific state and the country code - passing two variables to the cities page
$("#ddStates").change(function() {
$("#ddCity").load("includes/getCities.php",{choice3:$("#ddStates").val(),choice4:$("#ddCountryCodeGot").val()});
});
});

更新 虽然上面的方法是有效的 正如Du D在评论中也提到的那样 - 它也可以如下所示:

$("#ddCity").load("includes/getCities.php?choice3=" + $("#ddStates").val() + "&choice4=" + $("#ddCountryCodeGot").val());

2 个答案:

答案 0 :(得分:2)

这引出了我真正喜欢的jquery ajax方法的一个方面,即能够为作为HTTP params传递的URI提供值的哈希值。这允许您保留离散数据,避免将URI的字符串拼凑在一起的逃避噩梦。

在docs中引用.load的可选'data'原型:

.load( url [, data ] [, complete(responseText, textStatus, XMLHttpRequest) ] )

所以,你可以这样做:

$("#ddStates").load("includes/getStates.php",
                      {choice2: $("#ddCountry").val(),
                       choice4: $("#ddCountryCodeGot").val()
                      }
                    );

有时候,你必须深入研究文档,看看jquery和jquery插件如何将数据传递给这样的请求,但我更喜欢这种方法。

答案 1 :(得分:0)

您可以将任意数量的变量(最多为服务器的最大字符数)放入查询中,这是问号后面的部分。你用&符号分开它们。

示例,发送thing1 = x和thing2 = y:

page.php?thing1=x&thing2=y