Java 2017
$(document).ready(function() {
$("#submit").on('click', function() {
var formData = $("#addForm").serialize();
$.ajax({
type : "POST",
url : "addDanhMucMatHang", //Path action struts.xml
cache : false,
data : formData,
success : function(response) {
$('#message').html(response);
},
error : function(e) {
alert('Error: ' + e);
}
});
return false;
});
});
myAction.java
Java 2017
public class ItemAction {
private Item item;
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
// Insert Item
public String insertItem() throws IOException {
ItemDAO dao = new ItemDAO();
//True & false > insert
if (dao.insertItem(getItem())) {
return "success";
} else {
return "error";
}
}
}
public class Item {
private int itemID;
private String itemName;
private int itemAmt;
private Float itemUnitPrice;
private String itemUnitName;
private Float itemDisc;
private Float itemTotalAmt;
//Getter + Serter + Constructor
}
//Cách 2 sử dụng AJAX $.POST method
$(document).ready(function () {
// click on button submit
$("#submit").on('click', function () {
var maHang = $('#maHang').val();
var tenHang = $('#tenHang').val();
var soLuong = $('#soLuong').val();
var donGia = $('#donGia').val();
var donViTinh = $('#donViTinh').val();
var chietKhau2 = $('#chietKhau2').val();
var thanhTien2 = $('#thanhTien2').val();
$.post('addDanhMucMatHang', {
'item.itemID': maHang,
'item.itemName': tenHang,
'item.itemAmt': soLuong,
'item.itemUnitPrice': donGia,
'item.itemUnitName': donViTinh,
'item.itemDisc': chietKhau2,
'item.itemTotalAmt': thanhTien2
}, function (result) {
if (result.booleanCheck == "true") {
$('#message').text(result.booleanCheck);
} else {
$('#message').text(result.booleanCheck);
}
});
});
});
//Cách 2: $.POST
public String insertItem() throws IOException {
ItemDAO dao = new ItemDAO();
HttpServletResponse response = ServletActionContext.getResponse();
PrintWriter out = response.getWriter();
response.setContentType("application/json");
boolean result = dao.insertItem(getItem());
String jsonCheck;
if (result) {
System.out.println(result);
jsonCheck = "{\"booleanCheck\":\""+result+"\"}";
out.write(jsonCheck);
out.flush();
return NONE;
}
jsonCheck = "{\"booleanCheck\":\""+result+"\"}";
out.write(jsonCheck);
out.flush();
return NONE;
}
0 nhận xét:
Post a Comment