如何在Ajax响应中的multi Select中设置值?

时间:2018-06-29 06:42:57

标签: javascript ajax multi-select

function getNamefromDb(){
		var dataString = "metodo=getNames";
		
		$.ajax({
			type : "GET",
			url : "NameList.do",
			data : dataString,
			   dataType: "json",
			   async: false,
		        contentType: "application/json; charset=utf-8",
		        success : function(data) {
		        if (data.success == false) {
     				swal({
     					  title: data.message,
     					  html: true,
     					 
     					});
     				console.log("Fail"+data.message);
     			} else {
     				console.log("Success");
     				$.each(JSON.parse(data.message), function(key, value) {
     					$('#selectBoxId').append($("<option/>", {
     				        value: key,
     				        text: value
     				    }));
     				});
     				$("#selectBoxId").multiselect('rebuild');
     			}
		        }
     	});	
 	}
 <select id="selectBoxId" multiple="multiple"  onclick="javascript:getNamefromDb();">
在这里,我收到来自ajax调用的json响应。然后,我必须将这些值设置到选择框。可能吗? 但是无论如何,函数getNamefromDb()不会被调用。请说出问题所在。

2 个答案:

答案 0 :(得分:0)

您可以这样做:

  let dropdown = document.getElementById('selectBoxId');
    if (data.success){
    const data = JSON.parse(request.responseText);
    let option;
    for (let i = 0; i < data.length; i++) {
      option = document.createElement('option');
      option.text = data[i].value;
      option.value = data[i].key;
      dropdown.add(option);
    }}

答案 1 :(得分:0)

$('#selectBoxId').change(function() {
    var dataString = "{metodo:getNames,value:$(this).val()};
    $.ajax({
            type: "GET",
            url: "NameList.do",
            data: dataString,
            dataType: "json"
            async: false,
            success: function(response) {
                data = response;
                return response;
            },
            if (data.success == false) {


                swal({
                    title: data.message,
                    html: true,

                });
                console.log("Fail" + data.message);
            } else {
                console.log("Success");
                $.each(JSON.parse(data.message), function(key, value) {
                    $('#selectBoxId').append($("<option/>", {
                        value: key,
                        text: value
                    }));
                });
                $("#selectBoxId").multiselect('rebuild');
            }
        }
    });

}