无法使用Ajax调用返回的json数据创建select元素

时间:2013-11-09 14:25:52

标签: javascript jquery ajax json

我正在进行ajax调用以检索一些JSON对象。我说得对。但问题是当我想从返回的JSON创建一个select元素时,它不会创建一个或似乎是。

到目前为止我的JavaScript:

jQuery("#make").change(function () {
    var value = $(this).val();
    jQuery.getJSON("<?php echo site_url('ajax/get/models'); ?>", {
        makeId: value
    },

    function (data) {
        if (data != "false") {
            var modelsSelect = jQuery.createElement('select');
            var modelsOptions = "";
            var id;
            var model
            jQuery.each(data, function () {
                jQuery.each(this, function (key, value) {
                    if (key == "id") {
                        id = value;
                    } else {
                        model = value;
                    }
                });
                modelsOptions += "<option value=" + id + ">" + model + "</option>"
            });
            modelsSelect.innerHTML = modelsOptions;
            jQuery("#model").html = modelsSelect;
        } else {
            alert("false");
        }
    });
});

我返回的JSON格式:

Object { id="28", model="test model"}

来自ajax调用的返回响应中可能有 n 个JSON对象。

2 个答案:

答案 0 :(得分:2)

jQuery中没有createElement方法

jQuery.createElement应为document.createElement


也无需遍历对象的属性,您可以直接通过键访问它们

jQuery.each(data, function (index, item) {
    modelsOptions += "<option value=" + item.id + ">" + item.model + "</option>"
});

答案 1 :(得分:1)

更改此

jQuery("#model").html = modelsSelect;

jQuery("#model").html(modelsSelect);

<小时/> 参考

.html()

相关问题