【问题标题】:How to set values in multi Select from ajax response?如何从 ajax 响应中设置多选择中的值?
【发布时间】:2018-06-29 06:42:57
【问题描述】:

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');
     			}
		        }
     	});	
 	}
 &lt;select id="selectBoxId" multiple="multiple"  onclick="javascript:getNamefromDb();"&gt;
在这里,我收到来自 ajax 调用的 json 响应。然后我必须将这些值设置为选择框。是否可以? 但无论如何,不​​会调用函数 getNamefromDb() 。请告诉它有什么问题。

【问题讨论】:

标签: javascript ajax multi-select


【解决方案1】:

你可以这样做:

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

【讨论】:

    【解决方案2】:
    $('#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');
                }
            }
        });
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-22
      • 2012-10-05
      • 1970-01-01
      相关资源
      最近更新 更多