1

我的控制器中有这个:

  def selectmodels
    @brand = Brand.find_by_name(params[:brand_name])
    @models = Model.where(:brand_id => @brand.id)
    render json: @models
  end

返回的代码通过以下方式处理:

$.ajax({
    url: '/selectmodels?brand_name=' + test, type: 'get', 
    dataType: 'json',
    processData: false,
    success: function(data) {
        if (data == "record_not_found") {
            alert("Record not found");
        }
        else {
            alert(data);
            $('#style_model_name').autocomplete({ source: data });
        }
    }
});

我想将“数据”键和值加载到我的自动完成文本字段中。

谢谢!

更新:

我收到以下信息:

[{"brand_id":1,"created_at":"2012-04-09T03:12:43Z","id":1,"name":"x","updated_at":"2012-04-09T03:12:43Z"},{"brand_id":1,"created_at":"2012-04-09T03:15:54Z","id":2,"name":"y","updated_at":"2012-04-09T03:15:54Z"},{"brand_id":1,"created_at":"2012-04-09T09:33:59Z","id":5,"name":"z","updated_at":"2012-04-09T09:33:59Z"}]
4

1 回答 1

2
$.ajax({
    url: '/selectmodels?brand_name=' + test, type: 'get', 
    dataType: 'json',
    processData: false,
    success: function(data) {
        if (data == "record_not_found") {
            alert("Record not found");
        }
        else {
            var source = [];
            for (i in data) {
                for (k in data[i]) {
                    source.push(data[i][k]);
                }
            }
            $('#style_model_name').autocomplete({ source: source });
        }
    }
});

或者,如果您只想要某些字段:

$.ajax({
    url: '/selectmodels?brand_name=' + test, type: 'get', 
    dataType: 'json',
    processData: false,
    success: function(data) {
        if (data == "record_not_found") {
            alert("Record not found");
        }
        else {
            var source = [];
            for (i in data) {
                source.push(data[i]['name']);
                source.push(data[i]['id']);
                source.push(data[i]['brand_id']);
            }
            $('#style_model_name').autocomplete({ source: source });
        }
    }
});
于 2012-04-14T05:02:41.273 回答