繁体   English   中英

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

[英]How to send data to java servlet via ajax

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

我的UI

 $("#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 null

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

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);

}

我想到了这个想法,因为我没有办法解决,我只想知道解决这个问题的一些方法。 我要在其中插入此数据的数据库表如下所示:

这个

如果要在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。

您可以像下面的数据一样在jquery中使用数据标签:{Data1:Data1,Data2:Data2,Data3:Data3,}

尝试使用

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

并检查它是否仍然为空

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM