jquery表单提交给servlet

时间:2014-01-05 14:30:03

标签: java javascript jquery jsp servlets

我正在使用jquery表单提交给servlet。我正在向servlet发送xyz的值,当我提醒xyz它显示正确的值但在回调函数中数据警报显示为null这是我的脚本

<script>
    $(document).ready(function(){

          $("#country_id").change(function() {
             var xyz = $("option:selected").val();
              alert(xyz)
            //  var url ="../Retrive_country?stateadd_1=none&countryREF="+xyz;
                $.get("../Retrive_country?stateadd_1=none",
                {countryref : xyz } ,function(data,status){
            alert("Data: " + data + "\nStatus: " + status);
          });

            //$(location).attr('href',url);

        });
        });
        </script>

这是我的jsp

<html>
<body>
<div class="span2 clear">
<select name="country_id" id="country_id">
<option>-select-</option>

<option value="1" id="blabbb">1</option>
<option value="2" id="blabbb">2</option>
<option value="3" id="blabbb">3</option>
</select></div>
</body>
</html>

这是我的servlet ..

String countryref= request.getParameter("countryREF");
String sql1 = "SELECT * FROM state WHERE country_ref="+countryref+" ";
PreparedStatement pst1 = db.getConnection().prepareStatement(sql1);
 ResultSet j = pst1.executeQuery();
while (j.next()) {
                        String state_id = j.getString(1);
                        state = j.getString(2);
                        country_ref = j.getString(3);
                        location.setState(state);
                        location.setState_id(state_id);
                        location.setcountry_ref(country_ref);
                    }
pw.println(countryref);

我做错了什么?

2 个答案:

答案 0 :(得分:1)

您的服务器端代码在请求数据中需要countryREF(区分大小写),因此您可能只需要将$.get()中传递的数据更改为{ countryREF: xyz }

<script>
    $(document).ready(function(){
      $("#country_id").change(function() {
         //var xyz = $("option:selected").val();
         var xyz = $(this).val();

         alert(xyz);

         $.get("../Retrive_country?stateadd_1=none", { countryREF: xyz }, function(data,status){
           alert("Data: " + data + "\nStatus: " + status);
         });

      });
    });
</script>

答案 1 :(得分:0)

From the jQuery documentation,您可以尝试$.get的格式:

$(document).ready(function () {
    $("#country_id").change(function () {
        var xyz = $("option:selected").val();
        $.get("../Retrive_country?stateadd_1=none", {
            countryref: xyz
        })
            .done(function (data) {
            alert("Data Loaded: " + data);
        });
    });
});

OR:

$(document).ready(function () {
    $("#country_id").change(function () {
        var xyz = $("option:selected").val();
        $.get("../Retrive_country?stateadd_1=none&countryref=" + xyz, function (data) {
            alert("Data Loaded: " + data);

        });
    });
});