如何通过ajax在spring controller中发送复选框值?

时间:2016-12-19 03:46:21

标签: jquery ajax spring jsp

index.jsp如下所示。我的jsp页面中有一些复选框。我想将值发送到我的控制器,然后在单击“提交”按钮后在同一页面中显示它们。我想在我的控制器中发送复选框数据。

有一些图片。 After click the submit button,this is the ajax response in my alert

回复是:

{"country":"United State","favfruit":null,"firstName":"r4tr54","lastName":"tytu","gender":"Female","email":"ytuyui","fruit":[]}

这是我的index.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<script type="text/javascript" language="javascript" src="http://www.technicalkeeda.com/js/javascripts/plugin/jquery.js"></script>
<script type="text/javascript" src="http://www.technicalkeeda.com/js/javascripts/plugin/json2.js"></script>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring Jquery Ajax Demo</title>
<style>
Table.GridOne {
    padding: 3px;
    margin: 0;
    background: lightyellow;
    border-collapse: collapse;  
    width:35%;
}
Table.GridOne Td {  
    padding:2px;
    border: 1px solid #ff9900;
    border-collapse: collapse;
}
</style>
<script type="text/javascript">

function madeAjaxCall(){

     var country = $('#country').val();
     var gender = $('input:radio[name=sex]:checked').val();
     var checkboxValues = [];
     $('input.removeLater:checked').map(function() {
                 checkboxValues.push($(this).val());
     });
     alert(checkboxValues);
     var fruitstring = checkboxValues.toString();

    $.ajax({
        type: "post",
        url: "http://localhost:8080/SpringAjaxQuery/employee",
        cache: false,       

        data:'firstName=' + $("#firstName").val() 
            + "&lastName=" + $("#lastName").val() 
            + "&email=" + $("#email").val() 
            + "&gender=" + gender 
            + "&country=" + country
            + "&fruit=" + checkboxValues,

        success: function(response){
            $('#result').html("");
            var obj = JSON.parse(response);
            alert(response);
            $('#result').html(
                    "First Name:- " + obj.firstName 
              +"</br>Last Name:- " + obj.lastName  
              +"</br>Email:- " + obj.email 
              +"</br>Gender:- " + obj.gender 
              +"</br>Country:- " + obj.country
              +"</br>Fruit:-" + obj.fruit);
            document.forms["employeeForm"].reset();
        },

        error: function(){                      
            alert('Error while request..');
        }
    });
}
</script>
</head>
<body class="body">
    <form name="employeeForm" method="post">    
        <table cellpadding="0" cellspacing="0" border="1" class="GridOne">
            <tr>
                <td>First Name</td>
                <td><input type="text" name="firstName" id="firstName" value="" onfocus="clearThis(this)"></td>
            </tr>
            <tr>
                <td>Last Name</td>
                <td><input type="text" name="lastName" id="lastName" value=""></td>
            </tr>
            <tr>
                <td>Email</td>
                <td><input type="text" name="email" id="email" value=""></td>
            </tr>
            <tr>
                <td>Country</td>
                <td><select id="country">
                       <option value="None">-- Select --</option>
                       <option value="China">China</option>
                       <option value="United State">United State</option>
                       <option value="Malaysia">Malaysia</option>
                       <option value="Bangladesh">Bangladesh</option>
                      </select></td>
            </tr>
            <tr>
                <td id="genderradio">Gender</td>
                <td>        <input type="radio" name="sex" value="Male">Male</input>
                            <input type="radio" name="sex" value="Female">Female</input>
                            <input type="radio" name="sex" value="Unknown">Unknown</input>
                                                                                          </td>
            </tr>
             <tr>
                <td>Favourite Fruit</td>
                <td><input name="selector[]" id="ad_Checkbox1" class="removeLater" type="checkbox" value="Apple" />Apple
                    <input name="selector[]" id="ad_Checkbox2" class="removeLater" type="checkbox" value="Lichi" />Lichi
                    <input name="selector[]" id="ad_Checkbox3" class="removeLater" type="checkbox" value="Mango" />Mango
                    <input name="selector[]" id="ad_Checkbox4" class="removeLater" type="checkbox" value="Banana" />Banana</td>
            </tr>
            <tr>
                <td colspan="2" align="center"><input type="button" value="Ajax Submit" onclick="madeAjaxCall();"></td>
            </tr>
        </table>
    </form>
     <h1>Spring Framework Jquery Ajax</h1>
    <div id="result"></div>
</body>
</html>

这是我的控制器:

@RequestMapping(method = RequestMethod.POST)
 public @ResponseBody
 Employee add(HttpServletRequest request, HttpServletResponse response , ModelMap model)
   throws Exception {
  Employee employee = new Employee();
  String firstName = request.getParameter("firstName");
  String lastName = request.getParameter("lastName");
  String email = request.getParameter("email");
  String gender = request.getParameter("gender");
  String country = request.getParameter("country");
  String[] favfruit = (String[]) request.getAttribute("selector[]");
  employee.setEmail(email);
  employee.setFirstName(firstName);
  employee.setLastName(lastName);
  employee.setGender(gender);
  employee.setCountry(country);
  employee.setFavfruit(favfruit);

  return employee;
 }

我的模特是:

package com.pran.pal.simple.ajax.jquery.model;
import java.util.ArrayList;
import java.util.List;
public class Employee {

    private String firstName;
    private String lastName;
    private String email;
    private String gender;
    private String country;
    List <String> fruit = new ArrayList<String>();
    String[] favfruit;

    public String[] getFavfruit() {
        return favfruit;
    }

    public void setFavfruit(String[] favfruit) {
            this.favfruit = favfruit;           
    }

    public List<String> getFruit() {
        return fruit;
    }

    public void setFruit(List<String> fruit) {
        this.fruit = fruit;
    }

    public String getFirstName() {
        return firstName;
     }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

}

1 个答案:

答案 0 :(得分:1)

您正在使用

调用ajax
    $x=0;
    $data1[] = 0;
    $data2[] = 0;
    if($Rowdata1==null && $Rowdata2==null)
    {
        return 0;
    }
    else {


       foreach($Rowdata1 as $value){

            $mon = $value->monthOfTheYear;
            $day = $value->dayOfTheMonth;



            $dateD =  $this->year. '-' . $mon . '-' . $day;


            $data1[$x] = [
                'title' => $value->description,
                'start' => $dateD,
                'holiday' => '1'

            ];
           $x++;

        }

        foreach($Rowdata2 as $value){
            $year = ($value->yearID);
            $mon = $value->monthID;
            $day = ($value->dateID);

            $dateD = $year . '-' . $mon . '-' . $day;



            $data2[$x] = [
                'title' => $value->description,
                'start' => $dateD,
                'holiday' => '1'

            ];
            $x++;

        }
        if($data1==['0'] && $data2==['0'])
        {

          return 0;
        }
        elseif($data1==['0'])
        {

            return $data2;
        }
        elseif($data2==['0'])
        {

            return $data1;
        }
        else
        {
            unset($data2['0']);
            $data3 = array_merge($data1, $data2);

            return $data3;

        }


    }


}

但是尝试接收属性,将其转移到 data:'firstName=' + $("#firstName").val() + "&lastName=" + $("#lastName").val() + "&email=" + $("#email").val() + "&gender=" + gender + "&country=" + country + "&fruit=" + checkboxValues

在你的ajax成功回调中

request.getAttribute("selector[]")