如何在javascript中使用ajax将多个变量从jsp传递到servlet

时间:2016-11-15 06:28:56

标签: ajax jsp servlets

我是jspajax的新手。

如何使用xmlhttp.open("GET",servlet,false);ajax的{​​{1}}将多个变量传递给servlet。

我有两个选择框,比如姓名和电话号码,我需要将选定的值发送到servlet,在servlet中我将地址,城市像多个细节一样发送到jsp使用ajax。

2 个答案:

答案 0 :(得分:1)

jQuery.ajax({
        url : "<portlet:resourceURL id='URL'/>",
        data : {
            "A":value,
            "B":Value
        },type : "POST",
        dataType : "json",
        success : function(data) {
        }

答案 1 :(得分:0)

如果你想使用GET,你可以通过URL编码传递变量并将它们添加到url请求中,如下所示:

var url = "/path/to/myservlet";
var params = "somevariable=somevalue&anothervariable=anothervalue";
var http = new XMLHttpRequest();

http.open("GET", url+"?"+params, true);
http.onreadystatechange = function()
{
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send(null);

如果要传递长数据,使用POST是首选方法,以下是此类代码的示例:

var http = new XMLHttpRequest();
var url = "/path/to/myservlet";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

http.onreadystatechange = function() {//Call a function when the state changes.
  if(http.readyState == 4 && http.status == 200) {
      alert(http.responseText);
  }
}
http.send(params);

您将能够使用HttpServletRequest方法在servlet getParameter(String name)中读取这些数据。

希望这会有所帮助。 : - )