尝试使用JQUERY填充Select with JSON数据

时间:2016-01-29 16:34:00

标签: javascript jquery json ajax

看起来好像从ajax调用中检索数据一切都很好,但是我无法用JSON内容填充select,它会在控制台中一直触发此错误:

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in [{"0":"1","s_id":"1","1":"RTG","s_name":"RTG"},{"0":"2","s_id":"2","1":"IR","s_name":"IR"},{"0":"3","s_id":"3","1":"NCR","s_name":"NCR"},{"0":"4","s_id":"4","1":"RIG","s_name":"RIG"},{"0":"5","s_id":"5","1":"VND","s_name":"VND"}]

JS就是这个

function populateSelect(et_id){
    $.ajax({
        url: "http://localhost/new_dec/modules/Utils/searchAvailableStatus.php",
        type: "get", //send it through get method
        data:{et_id:et_id},
        success: function(response) {
            var $select = $('#newStatus');                          
            $.each(response,function(key, value) 
            {
                $select.append('<option value=' + key + '>' + value + '</option>');
            });
        },
        error: function(xhr) {
            //Do Something to handle error
        }
    });
}

JSON看起来像这样:

[{"0":"1","s_id":"1","1":"RTG","s_name":"RTG"},{"0":"2","s_id":"2","1":"IR","s_name":"IR"},{"0":"3","s_id":"3","1":"NCR","s_name":"NCR"},{"0":"4","s_id":"4","1":"RIG","s_name":"RIG"},{"0":"5","s_id":"5","1":"VND","s_name":"VND"}]

2 个答案:

答案 0 :(得分:1)

假设您的服务器端脚本没有设置正确的Content-Type:application / json响应头,您需要解析对Json的响应。

然后你可以使用$ .each()函数循环遍历数据:

var json = $.parseJSON(response);

答案 1 :(得分:1)

我认为你需要这样的东西。

function populateSelect(et_id){
    $.ajax({
        url: "http://localhost/new_dec/modules/Utils/searchAvailableStatus.php",
        type: "get", //send it through get method
        data:{et_id:et_id},
        success: function(response) {
            var json = $.parseJSON(response);
            var $select = $('#newStatus');                          
            $.each(json ,function(index, object) 
            {
                $select.append('<option value=' + object.s_id+ '>' + object.s_name+ '</option>');
            });
        },
        error: function(xhr) {
            //Do Something to handle error
        }
    });
}