dongtao1262
dongtao1262
2016-07-25 05:37

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

I don't know what the title should be, hehe but anyone know how to get select2 data from ajax response

here my code:

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',
    });

}

I don't know why it doesn't work, haha

the response like this

[{"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"}]

I want to get the allowance_id and allowance_name

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • doulipi3742 doulipi3742 5年前

    Go with below code flow

    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();
    
        }
      });
    
    }
    
    点赞 评论 复制链接分享

为你推荐