0

我有两个选择。第二个选择值取决于第一个。当用户在第一个选择中选择一个值时,会调用一个 Action 来填充第二个选择。它仅在用户提交表单并且存在验证错误时才有效。

当用户在第一个选择中选择一个值时,如何重新加载 div?

我的jQuery是:

$('select[name=select1]').change(function () {
            var cod=$(this).val();
            if (cod>0) {
                $.ajax({
                    url:"Load.do",
                    data: "cod="+cod,
                    });
            }
        });

在 struts-config.xml 中,我有:

<action path="/Load" scope="request" type="mypackage.Load">
    <forward name="Success" path="/jsp/myForm.jsp"/>
 </action>

类 Load 是一个动作:

public class Load extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
{
    // TODO Auto-generated method stub

    Connection con = null;
    Statement stmt = null;
    ResultSet rs = null;

    try {
        // get the connection 
        stmt = (Statement) con.createStatement();

        String cod = request.getParameter("cod");

        String select = new String("Select firstCode, name from mytable where secondCode = '");
        select = select.concat(cod);
        select = select.concat("';");
        rs = stmt.executeQuery(select);
        ArrayList<LabelValueBean> arr = new ArrayList<LabelValueBean>();            
        while (rs.next()) {
            arr.add(new LabelValueBean(rs.getString("name"),rs.getString("firstCode")));
        }

        request.getSession().setAttribute("arr", arr);

        return mapping.findForward("Success");
    } catch (NamingException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    }  catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (rs != null) {
              try { rs.close(); } catch (SQLException e) {}
              rs = null;
        }
        if (stmt != null) {
              try { stmt.close(); } catch (SQLException e) {}
              stmt = null;
        }
        if (con != null) {
              try { con.close(); } catch (SQLException e) {}
              con = null;
        }        
    }

    return mapping.findForward("Failure");
}
 }

在我的 myForm.jsp 页面中,我要填写的选择是:

 <html:select property="prop1">
 <html:option value="0">Choose:</html:option>
 <% if (request.getSession().getAttribute("arr") != null) { %>
<html:optionsCollection name="arr" label="label" value="value"/>
<% } %>
</html:select>
4

1 回答 1

0

如果响应数据包含您想要的 html,即<select>所有选项都正确,您可以简单地将第二个选择替换为响应数据:

$('select[name=select1]').change(function () {
    var cod=$(this).val();
    if (cod>0) {
        $.ajax({
            url:"Load.do",
            data: "cod="+cod,
            success: function(result) {
                $('select[name=select2]').replaceWith(result); //guessing the name
            }
        });
    }
});
于 2012-11-06T15:52:40.610 回答