如何通过ajax调用将列表放入select中

时间:2014-05-27 08:33:51

标签: javascript jquery ajax jsp struts2

我通过ajax调用将动作列表发送到jsp,我将列表设置为hashmap的元素,以便将其放入下拉列表<s:select>,如下所示:

行动:

public String query()
    {
         Map<String, Object> map= new HashMap<>();

        operationservice = new OperationServiceImpl();
        operation = operationservice.getOperationById(id);
        tiers = operationservice.getAll();
                SimpleDateFormat format2 = new SimpleDateFormat("dd/MM/yyyy");

                tiersnoms =  new ArrayList<String>();
                for (int i = 0; i < tiers.size(); i++) {
            String t = tiers.get(i).getNom();
            if(t != null || t!= "")
                tiersnoms.add(t);
        }

        map.put("Dt_debut", format2.format(operation.getDt_debut()));
        map.put("Dt_fin", format2.format(operation.getDt_fin()));
        map.put("Montant",operation.getMontant() );     
        map.put("Tiernomm",tiersnoms);
return "success";
}

jsp - ajax调用:我想将tiersnoms元素放入我的选择标记

$.ajax(
        {
            type: 'POST', 
            url  : "<s:url action='query'/>",
            dataType : 'json',
            data: { id : id },
            success: function(result){

                $.each(result, function(key,value)

                {   $("#"+key, myModal).val(value); // pass all values to each textfield
                        if ( key === "Tiernomm") //put a list into select 
                    {
                                        $('#Tiernomm').empty();
                                        $('#Tiernomm').append($('<option>    </option>').val('').text('Selectionnez--'));
                                    $.each(value, function (i, item) {
                            $('#Tiernomm').append($('<option></option>').val(item.key).text(item.value));
                        });
                    }

                            } );

        },

         });

struts.xml中

<action name="query" class="action.Operations"
            method="query">
            <result name="success" type="json" >
                    <param name="root">map</param>
                </result>           
        </action>

运行此代码后:我的select有一些空行但这些行没有值?

1 个答案:

答案 0 :(得分:0)

我解决了这个问题:这是一个javascript错误

$.each(result, function(key,value)

                    {   $("#"+key, myModal).val(value);
                    if ( key === "Tiernomm")
                        {
                            $('#Tiernomm').empty();
                            $('#Tiernomm').append($('<option></option>').val('').text('Selectionnez--'));
                            $.each(value, function (i,item) {

                                $('#Tiernomm').append($('<option></option>').val(item).text(item));
                            });
                        }

                                } );