如何从ajax响应中获取select2数据

时间:2016-07-25 05:37:45

标签: php jquery ajax select2

我不知道标题应该是什么,呵呵 但任何人都知道如何从ajax响应中获取select2数据

这里是我的代码:

function selectData(){
    $('#select-data').select2({
    tags: true,
    data: arr_data,
});
}


var arr_data = dataArr();

function dataArr(){
  $.ajax({
    url: SITE_URL + 'position/allowance_get',
    dataType: 'json',
    });

}

我不知道为什么它不起作用,哈哈

像这样的回应

[{"allowance_id":"1","position_id":"1","allowance_name":"Tunjangan Kendaraan","allowance_value":"1000000"
},{"allowance_id":"10","position_id":"4","allowance_name":"Tunjangan Istri Tua","allowance_value":"1000000"
},{"allowance_id":"11","position_id":"4","allowance_name":"Tunjangan Istri Muda","allowance_value":"1000000"
},{"allowance_id":"29","position_id":"10","allowance_name":"Allowance Lipstic","allowance_value":"500000"
},{"allowance_id":"30","position_id":"10","allowance_name":"Allowance Powder","allowance_value":"600000"
},{"allowance_id":"31","position_id":"10","allowance_name":"Allowance Dalaman","allowance_value":"1000000"
},{"allowance_id":"32","position_id":"11","allowance_name":"Allowance Tunjangan","allowance_value":"20000000"
},{"allowance_id":"33","position_id":"11","allowance_name":"Allowance Kendaraan","allowance_value":"5000000"
},{"allowance_id":"34","position_id":"12","allowance_name":"Tunjangan Keluarga","allowance_value":"1000000"
},{"allowance_id":"35","position_id":"12","allowance_name":"Tunjangan Transportasi","allowance_value"
:"2000000"},{"allowance_id":"36","position_id":"12","allowance_name":"Tunjangan Hari Raya","allowance_value"
:"10000000"},{"allowance_id":"39","position_id":"13","allowance_name":"Tunjangan Makan","allowance_value"
:"2000000"},{"allowance_id":"40","position_id":"13","allowance_name":"Tunjangan Minum","allowance_value"
:"400000"},{"allowance_id":"41","position_id":"15","allowance_name":"Tunjangan Dinas","allowance_value"
:"23234343434"}]

我想获得allowance_id和allowance_name

1 个答案:

答案 0 :(得分:0)

使用以下代码流

var arr_data = [];

function selectData(){
    $('#select-data').select2({
      tags: true,
      data: arr_data,
    });
}

function dataArr(){
  $.ajax({
    url: SITE_URL + 'position/allowance_get',
    dataType: 'json',
    success : function(data) {
      var tempObj = {};
      for(var i = 0; i < data.length; i++){
        tempObj = {"id":data[i].allowance_id,"text":data[i].allowance_name};
        arr_data.push(tempObj);
      }
      selectData();

    }
  });

}