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”}]

更多相关文章

  1. $ .post请求中的回调函数
  2. 利用jQuery的$.event.fix函数统一浏览器event事件处理
  3. 仅当鼠标停留在元素上时,jQuery才会激活鼠标悬停函数
  4. jQuery循环没有每个和回调函数
  5. JavaScript函数中的Ruby代码
  6. jQuery.parseJSON()函数详解
  7. 从内部获取函数名称
  8. Jquery 1.9, JS -函数在Chrome中没有定义
  9. 将php jsonencode数组结果显示为ajax成功函数

随机推荐

  1. 谈谈​PHP防止XSS跨站脚本攻击的方法
  2. 超简单开发自己的php框架一点都不难!
  3. 详细解说PHP中break、continue、return、
  4. php抽象类和接口之间有什么区别?
  5. PHP中什么是命名空间?为什么使用命名空间?
  6. 一起聊聊php中的传统三层架构
  7. 手把手教你学PHP,学习心得分享!!
  8. 详解PHP中PHP-FPM是什么?有什么用?
  9. 带你了解php的三个常用框架:thinkphp、yaf
  10. PHP解析XML的几种方法(附代码)