使用jquery将参数传递给控制器

时间:2013-12-18 06:51:11

标签: java jquery

我创建了一个视图和控制器,我试图使用jquery将表单参数传递给控制器​​..

  $.ajax({  
    type: "POST",  
    url: "add.htm", 
    datatype: "json",
    data: "name=" + name + "&password=" + password + "&gender=" + gender + "&aboutyou=" + aboutyou, 
    success: function(response){
        alert(response.name);
      // we have the response 
      if(response.status == "SUCCESS"){
          $('#info').html("User has been added to the list successfully");
          /* $('#name').val('');
          $('#education').val(''); */
      }else{
          $('#info').html("Sorry, there is some thing wrong with the data provided.");
      }       
    },  
    error: function(e){  
      alert('Error: ' + e);  
    }  
  });  
}  

这是我的控制器。

      public ModelAndView add(HttpServletRequest request,
        HttpServletResponse response, employee employee) throws Exception {
    List list=new ArrayList();
    employeedao.saveUser(employee);
    return new ModelAndView("userform");
}

4 个答案:

答案 0 :(得分:1)

我认为您想要获取控制器中的值(来自问题标题),如果这是要求,则使用request.getParameter("parametername");

例如,要获取名称,请执行此操作

request.getParameter("name"); 

您还需要更改传递参数的格式,如

data:{parametername:parametervalue}作为JSON

示例data:{name:name ....}

答案 1 :(得分:0)

替换您的以下行: -

 data: "name=" + name + "&password=" + password + "&gender=" + gender + "&aboutyou=" + aboutyou,

以下行: -

 data: { name:name,password:password,gender:gender,aboutyou:aboutyou}

答案 2 :(得分:0)

您的数据格式不正确

请参阅http://api.jquery.com/jQuery.post/

格式为

{ name: "John", time: "2pm" }

答案 3 :(得分:0)

您已经像普通数据一样发送了数据,但在jquery中,格式的变化如下所述

$.ajax({  
type: "POST",  
url: "add.htm", 
datatype: "json",
data: { "name":name,"password":password,"gender":gender,"aboutyou":aboutyou},
success: function(response){
    alert(response.name);
  // we have the response 
  if(response.status == "SUCCESS"){
      $('#info').html("User has been added to the list successfully");
      /* $('#name').val('');
      $('#education').val(''); */
  }else{
      $('#info').html("Sorry, there is some thing wrong with the data provided.");
  }       
},  
error: function(e){  
  alert('Error: ' + e);  
}  
  });  
}  

这是发送数据的格式。 谢谢 纳温