更新与其中的列表;选择>使用jQuery和Ajax选项 [英] Updating list of <select> options using jquery and ajax

查看:118
本文介绍了更新与其中的列表;选择>使用jQuery和Ajax选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据于在先前的HTML选择对象的选择,使选择更新的HTML选择列表。我的jQuery是如下。这是被称为正常。

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.

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]));
    }
});

由于我使用的是单用我的MySQL数据库的接口,这个jQuery函数调用一个'中间人'叫updateTypes.php PHP文件是如下:

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:

include 'databaseInterface.php';
$brand = $_GET["q"];
$typesData = databaseInterface::getBrandTypes($brand);
return $typesData;

这下面我单身调用getBrandTypes功能:

This calls the getBrandTypes function in my singleton below:

$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);

的网页正确地移除从jQuery功能的现有选项,但无法对其进行更新。看来出问题的时候c。在jQuery的JSON数据我去$ C $。为什么会错?是循环更新的选择对象合适吗?

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?

推荐答案

您可以使用 $。的getJSON 如果你期待一个JSON响应。您可能还可以使用 $。每(),然后简单地 .append()选择标记。您可以参考 this.property 里面的每个()

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().

类似如下:

$.getJSON("updateTypes.php?q="+brandName, function(data) {
    $("#Type").remove();
    $.each(data, function(){
        $("#Type").append('<option value="'+ this.value +'">'+ this.name +'</option>')
    )
})

这会假设你的JSON响应是类似以下内容:

This would assume your json response is something like the following:

[{名富,值:酒吧},{名字:另一个,值:榜样}]

这篇关于更新与其中的列表;选择&GT;使用jQuery和Ajax选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆