jQuery appendTo(), json 在 IE 6,7,8 中不起作用

4 javascript php jquery json

两天来,我一直在绞尽脑汁,试图为此找到解决方案。我正在使用 jQuery.ajax() 从数据库中获取值以在更改另一个框时更新一个框。php 脚本从数据库中获取值,然后吐出 json。它在 FF 中工作正常,但在所有版本的 IE 中,选择框都没有更新。我已经确认输出的 json 是好的。

这是jquery:

function getVendors(dest, selectSup) {
  var vend = $('select#sup').val();
  $.ajax({
    beforeSend: function() {
      $("select#dest").parent().addClass('loading');
    },
    type: "GET",
    dataType: "json",
    cache: false,
    url: '/search/cruiseselect/?type=vendors&supplier=' + vend + '&dest=' + dest,
    timeout: 2000,
    error: function() {
      alert("Failed to submit");
    },
    success: function(data) {
      $("select#sup option").remove();
      var any = "<option value=\"any\">-- All Cruise Lines --</option>";
      $(any).appendTo("select#sup");
      $.each(data, function(i, j) {
        if (j != null && j != undefined) {
          var sel = j.value == selectSup ? " selected" : "";
          var row = "<option value=\"" + j.value + sel + ">" + j.text + "</option>";
          //$(row).appendTo("select#sup");                  
          $("select#sup").append(row);
        }
      });
    },
    complete: function() {
      $("select#dest").parent().removeClass('loading');
    }
  });
}
jQuery(document).ready(function() {

  //dynamic select boxes 
  $("select#dest").change(function() {
    var selectSup = $("select#sup").children("option:selected").val();
    getVendors($(this).val(), selectSup);
  });
});
Run Code Online (Sandbox Code Playgroud)

我在我的 php 中有这个

header('Cache-Control: no-cache, must-revalidate');

header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');

header('Content-type: application/json');


echo json_encode($json);
Run Code Online (Sandbox Code Playgroud)

And it's outputting the correct json with no extra commas or anything. What's more is that If I use alert(j.value + j.text); in my .each() loop, I get the correct data in IE so it seems that it's the jquery appendTo() that's not working.

Anybody got any ideas?

scu*_*ffe 5

我有点惊讶 jQuery 没有处理这个(我认为它做了......也许它的 .html() 有效)。

该问题基于IE (6,7,& 8) 错误,您无法设置选择列表的 .innerHTML

使用“vanilla”Javascript,您可以使用 Option 对象创建新选项并将它们添加到选择中,或者您可以一次设置整个选择列表(例如,包括选择标签)。

var mySelect = $("select#sup").get(0);//get actual DOM element
var newOpt,selLen;
for(var i=0;i<10;i++){
  newOpt = new Option('Label: ' + i, i);
  //format new Option(text, value, defaultSelected, selected);
  //add new option to select object
  selLen = mySelect.options.length;
  mySelect.options[selLen] = newOpt;

  //This may also work, but I don't recall if IE6 supports the .push()
  //method on the options collection, if so, this line will replace the 2 above
  //    mySelect.options.push(newOpt);
}
Run Code Online (Sandbox Code Playgroud)