使用jquery和ajax更新选项列表
I am trying to make an html select list of options update according to a selection made on a prior html select object. My jquery is below. This is being called correctly.
我试图根据在先前的html选择对象上做出的选择来更新选项列表。我的jquery在下面。这被正确调用。
var brandName = $("#Brand").val();
$.get("updateTypes.php?q="+brandName, function(data) {
$("#Type").remove();
var typeData = JSON.parse(data);
for (loop=0; loop < typeData.length; ++loop) {
$("#Type").options.add(new Option(typeData[loop]));
}
});
As I am using a singleton to interface with my mySQL database, this jquery function calls a 'go-between' .php file called updateTypes.php which is below:
当我使用单例与我的mySQL数据库接口时,这个jquery函数调用一个名为updateTypes.php的“中间”.php文件,如下所示:
include 'databaseInterface.php';
$brand = $_GET["q"];
$typesData = databaseInterface::getBrandTypes($brand);
return $typesData;
This calls the getBrandTypes function in my singleton below:
这将在我的单例中调用getBrandTypes函数:
$query = "SELECT psTypeName FROM types WHERE brands_psBrandName='$BrandName'";
$result = mysqli_query($con, $query) or die ("Couldn't execute query. ".mysqli_error($con));
$resultArray = array();
while ($row = mysqli_fetch_assoc($result)) {
extract($row);
$resultArray[] = $psTypeName;
}
return json_encode($resultArray);
The webpage correctly removes the existing options from the jquery function but fails to update them. It seems to go wrong when I decode the JSON data in the jquery. Why is it going wrong? Is the loop for updating the select object appropriate?
网页正确地从jquery函数中删除现有选项,但无法更新它们。当我在jquery中解码JSON数据时似乎出错了。为什么会出错?更新选择对象的循环是否合适?
2 个解决方案
#1
17
You can use $.getJSON
if your expecting a json response. You might also be able to use $.each()
and then simply .append()
to the select
tag. You can reference this.property
inside the .each()
.
如果您期望json响应,可以使用$ .getJSON。您也可以使用$ .each()然后简单地使用.append()到select标签。您可以在.each()中引用this.property。
Something like the following:
类似于以下内容:
$.getJSON("updateTypes.php?q="+brandName, function(data) {
$("#Type").remove();
$.each(data, function(){
$("#Type").append('<option value="'+ this.value +'">'+ this.name +'</option>')
)
})
This would assume your json response is something like the following:
这将假设您的json响应类似于以下内容:
[ { name : "foo", value : "bar" }, { name : "another", value : "example" } ]
[{name:“foo”,value:“bar”},{name:“another”,value:“example”}]
更多相关文章
- $ .post请求中的回调函数
- 利用jQuery的$.event.fix函数统一浏览器event事件处理
- 仅当鼠标停留在元素上时,jQuery才会激活鼠标悬停函数
- jQuery循环没有每个和回调函数
- JavaScript函数中的Ruby代码
- jQuery.parseJSON()函数详解
- 从内部获取函数名称
- Jquery 1.9, JS -函数在Chrome中没有定义
- 将php jsonencode数组结果显示为ajax成功函数