我正在创建一个需要使用jQuery提交的表单。下面是我的代码-
<script src="js/app.js" type="text/javascript"></script>
<form method="post" class="needs-validation" id="new-item" action="admin-add-inventory2.php">
<div class="mb-3">
<label>Item Name</label>
<input type="text" class="form-control" id="itemname" name="itemname" placeholder="Item name" required>
<span id='inmessage'>
</div>
<div class="mb-3">
<label>Description
<span class="text-muted">(Optional)</span>
</label>
<input type="text" class="form-control" id="description" name="description" placeholder="description...">
<span id='dmessage'>
</div>
<hr class="mb-4">
<input type="submit" value="Add To Inventory" name="submit" id="submit" class="btn btn-primary btn-lg btn-block error-w3l-btn">
</form>
<div id="form-messages"></div>
app.js的代码-
$(function() {
// Get the form.
var form = $('#new-item');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#itemname').val('');
$('#description').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured, please try again.');
}
});
});
});
但是,当按下提交按钮时, app.js 无法执行。它直接进入表单标签的 action =“ admin-add-inventory2.php” 。
请指出我缺少的逻辑。
由于更多的代码和更少的文本,所以它在stackoverflow中没有问题,所以我要添加额外的文本来提交。请忽略以下文本。
但是,当按下提交按钮时, app.js 无法执行。它直接进入表单标签的 action =“ admin-add-inventory2.php” 。
请指出我缺少的逻辑。
但是,当按下提交按钮时, app.js 无法执行。它直接进入表单标签的 action =“ admin-add-inventory2.php” 。
请指出我缺少的逻辑。
答案 0 :(得分:2)
请从提交到按钮替换按钮类型。
例如:<input type="button" value="Add To Inventory" name="submit" id="submit" class="btn btn-primary btn-lg btn-block error-w3l-btn">
如果您想通过单击按钮来调用JS文件中的AJAX代码,请用$(form).submit(function(e) {
替换$("#submit").click(function(e) {
。