<script type="text/javascript">
jQuery(window).load(function() {
alert('page is loaded');
});
function savefun() {
$.ajax({
type: "GET",
url: "AddController",
data: {
name: $('#name').val(),
price: $('#price').val()
},
success: function(data) {
if (data.flag1 == true) {
console.debug("true");
} else {
}
}
});
}
</script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: 'DisplayController',
type: 'GET',
success: function(response) {
var trHTML = '';
$.each(response, function(i, item) {
trHTML += '<tr><td>' + item.name + '</td><td>' + item.id + '</td><td>' + item.price +
'</td><td>' + '<button id="' + item.id + '" class="btn">Delete</button>'
'</td></tr>';
});
$('#delTable').append(trHTML);
$('button').click(function() {
var val = $(this).attr("id");
console.debug("saurabh userid", val);
var rowElement = $(this).parent().parent();
$.ajax({
type: "POST",
data: {
productid: val
},
url: "DisplayController",
success: function(result) {
rowElement.find('td').fadeOut('3000',
function() {
rowElement.remove();
});
}
});
});
}
});
});
</script>
<table id="delTable" border=1 align="center" height="150" width="200">
<thead>
<tr>
<th width="100">Product Name</th>
<th width="100">Price</th>
<th width="100">Id</th>
<th width="100">Delete</th>
</tr>
</thead>
</tbody>
</table>
<h3 align="center">Add a New Product</h3>
<form>
Product Name : <input id="name" type="text" name="name">
Product Price : <input id="price" type="number" name="price">
<input type="submit" value="Save" align="middle" onclick="savefun()">
</form>
我正在尝试使用AJAX调用添加产品/项目。我写了savefun()
来做这件事。当我添加产品时,页面正在刷新,这不应该发生,它应该添加而不刷新。我该如何解决这个问题?
答案 0 :(得分:0)
如果您从onclick
功能更改按钮onsubmit
以形成return false
和savefun()
。
<form onsubmit="return savefun();">
Product Name : <input id="name" type="text" name="name">
Product Price : <input id="price" type="number" name="price">
<input type="submit" value="Save" align="middle">
</form>
function savefun() {
$.ajax({
type: "GET",
url: "AddController",
data: {
name: $('#name').val(),
price: $('#price').val()
},
success: function(data) {
if (data.flag1 == true) {
console.debug("true");
} else {
}
}
});
return false;
}
但是还有其他方法可以使用jQuery。
$('[yourFormSelector]').on('submit', function(event){
savefun();
event.preventDefault();
})