如何通过Ajax将数据发送到Java Servlet

时间:2019-06-11 06:50:29

标签: javascript java jquery html servlets

我有一个UI,其中有一些开关形式的复选框,当用户单击该按钮时,我也有一个按钮。on click事件是我正在运行ajax将数据发送到我的后端,保存到我的数据库中。

我的用户界面

$("#btn").on('click', function() {
  $.ajax({
    'url': 'DisplayImage',
    'method': 'POST',
    'data': formToJSON(),
    'success': function(data) {

    },

    complete: function() {

    },
    'error': function(err) {

    }
  })

  function formToJSON() {
    return JSON.stringify({
      ImageData: tableData,
    });
  };
})
.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
  float: right;
}


/* Hide default HTML checkbox */

.switch input {
  display: none;
}


/* The slider */

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input.success:checked+.slider {
  background-color: #8bc34a;
}

input:checked+.slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}


/* Rounded sliders */

.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<div class="container">
  <div class="row">

    <div class="col-md-6">
      <div class="card" style="margin: 20px 0">
        <div class="card-header">Counter A</div>

        <ul class="list-group list-group-flush">

          <li class="list-group-item">CounterA1.jpg <label class="switch "> <input type="checkbox" class="success" >
								<span class="slider round" ></span>
						</label>
          </li>
          <li class="list-group-item">CounterA2.jpg <label class="switch "> <input type="checkbox" class="success">
								<span class="slider round"></span>
						</label>
          </li>

        </ul>
        <div class="card-header">Counter B</div>

        <ul class="list-group list-group-flush">

          <li class="list-group-item">CounterB1.jpg <label class="switch "> <input type="checkbox" class="success">
								<span class="slider round"></span>
						</label>
          </li>

        </ul>
        <div class="card-header">Counter C</div>

        <ul class="list-group list-group-flush">

          <li class="list-group-item">CounterC1.jpg <label class="switch "> <input type="checkbox" class="success">
								<span class="slider round"></span>
						</label>
          </li>

        </ul>
      </div>
    </div>
  </div>
</div>
<button id="btn"> Go</button>

我试图将所有这些都转换为这样的JSON

var tableData = {"Counter A": {"Name": "CountA1.jpg","IsActive.jpg":"Y"}} 

但是有两个问题:-

  • 当我尝试输入Counter B数据时也说不是有效的JSON
  • 当我通过doPost将其发送到后端时,它consoles为空

我不知道怎么了。我需要改变我的方法吗?

Ajax代码

  $("#btn").on('click',function(){
        $.ajax({ 
        'url': 'DisplayImage', 
        'method': 'POST', 
        'data' : formToJSON() ,
        'success': function(data){ 
        }, 
        complete: function(){
        },
        'error': function(err){ 
        } 
    })
    function formToJSON() 
    {
         return JSON.stringify({ImageData:tableData,});
    };
})

Servlet doPost

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String imageData = request.getParameter("ImageData");
    System.out.println(imageData);

}

由于我缺乏解决方法,因此想到了这个想法,我只想知道解决此问题的一些方法。我要在其中插入数据的数据库表如下:

This

3 个答案:

答案 0 :(得分:1)

如果要在JSON数组中使用“ counterA”和“ counterB”,则需要创建如下所示的JSON。

var tableData = [{ "Counter A": [{ "Name": "CountA1.jpg", "IsActive.jpg":"Y" } ,{"Name": "CountA2.jpg", "IsActive.jpg":"N"}]},
                 { "Counter B": { "Name": "CountB1.jpg", "IsActive.jpg":"Y" } } ];

或者您可以将json数组转换为

var tableData = [ { "Counter": "Counter A", "Name": "CountA1.jpg", "IsActive.jpg":"Y" }  ,
                  { "Counter": "Counter A", "Name": "CountA2.jpg", "IsActive.jpg":"N" } ,
                  { "Counter": "Counter B", "Name": "CountB1.jpg", "IsActive.jpg":"Y" }  ];

要在数据库中插入JSON数据,建议您使用Google。 但是出于一点了解,我在下面发布了代码和声明,对您有帮助。

  

创建模型类,   例如:Counter.java

private String counter;
private String img;
private String flag;

public void setCounter(String counter){this.counter=counter;}
public String getCounter(){return this.counter;}

//Same getter and setter methods for img and flag.
  

现在回到您的主要班级

 JSONArray jArray=new JSONArray(request.getParameter("ImageData"));
 JSONObject obj;
 JSONParser parser = new JSONParser();
 List<Counter> lstCounter = new ArrayList<Counter>();
 Counter counter = new Counter();

 //Create Loop which iterates your jArray
{
     JSONObject obj = (JSONObject)parser.parse( < jArray[iterator.next()] >  ) //Here you need to parse the each your JSON and convert one by one in jsonobject
     Ex: { "Counter": "Counter A", "Name": "CountA1.jpg", "IsActive.jpg":"Y" } as your first line you can extract the first row.

     //Store the row in Model Counter as a list
     counter = new Coutner();
     counter.setCounter( <read data from json array> );
     //same thing for img and flag then add to lstCounter
    lstCounter.add( counter);
}

循环完成后,您将拥有与普通插入操作相同的准备好存储在数据库中的listArray。

答案 1 :(得分:0)

您可以在jquery中使用数据标签,如下所示 数据:{                     数据1:数据1,                     数据2:数据2,                     Data3:Data3,}

答案 2 :(得分:-1)

尝试使用

Scanner scanner = new Scanner(request.getInputStream())
String imageData = scanner.nextLine();

并检查它是否仍然为空