如何在不使用表单的情况下将文本字段数据从html传递到servlet

时间:2014-03-15 09:50:55

标签: java javascript ajax jsp java-ee

我正在建立一个在线购物网站。我想为用户提供一个选项,他/她可以选择不同的送货地址: -       

送货明细

         <input type="button" value="Same as billing address"   style="color: #FFFFFF;" class="link-style" onclick="test();"  />
             <table cellpadding="20">
                    <tr>
                        <td >Name : * </td>
                        <td><input type="text" id="name" name="name" /></td>

                    </tr>
                     <tr>
                        <td>Contact Number : </td>
                        <td><input type="text" name="cno" id="cno"  /></td>
                    </tr>
                    <tr>
                        <td>Address : * </td>
                        <td><input type="text" name="address "id="address" /></td>
                    </tr>

                    <tr>
                        <td>City : *</td>
                        <td><input type="text" name="city" id="city"  /></td>
                    </tr>
                    <tr>
                        <td>State : * </td>
                        <td><input type="text" name="state" id="state" /></td>
                    </tr>
                    <tr>
                        <td>Country : *</td>
                        <td><input type="text" name="country" id="country" /></td>
                    </tr>


                </table>                

如果用户点击按钮,则禁用所有字段。否则他/她可以填写不同的送货地址。问题是我不想在这里使用表单。如何在会话或发布中将这些参数传递给jsp或servlet?我已经尝试过AJAX,但我无法正常使用它

function setValue() {
    alert("hi");
    var name = document.getElementById("name").value;
    var cno = document.getElementById("cno").value;
    var address = document.getElementById("address").value;
    var city = document.getElementById("city").value;
    var state = document.getElementById("state").value;
    var country = document.getElementById("country").value;
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.open("post", "test.jsp", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-      urlencoded");
    xmlhttp.send("name=" + name);
    xmlhttp.send("cno=" + cno);
    xmlhttp.send("address=" + address);
    xmlhttp.send("city=" + city);
    xmlhttp.send("state=" + state);
    xmlhttp.send("country=" + country);



}

Test.jsp没有获取参数。

2 个答案:

答案 0 :(得分:1)

您必须只调用xmlhttp.send一次,这需要您连接请求参数。

 xmlhttp.send("name="+name+"&cno="+cno+"&address="+address+"&city="+city+"&state=" + state + "&country="+country);

答案 1 :(得分:0)

尝试这样:

var inputParam='{"name":"'+name+'","cno":"'+cno+'","address":"'+address+'","city":"'+city+'","state":"'+state+'","country":"'+country+'"}';

$.ajax({
        type: "POST",
        url: your base_url,
        data: {inputParam:inputParam,module :'your module name'},
        dataType: "json",
        async:false,
        success: function(msg)
        {
             console.log(msg);
        }
    });