这个问题已被提出并回答了很多次。我在SO周围搜索过,无法找到有效的解决方案。我尝试了e.preventdefault()
和return false
。都没有奏效。然后我看到我需要回到AJAX并且不能使用承诺而我拒绝这样做,我拒绝认为没有办法用承诺做到这一点。
无论如何,
代码:
var submitDataForm = function () {
console.log("button called");
var email = document.getElementById('email');
var first = document.getElementById('first-name');
var last = document.getElementById('last-name');
var web = document.getElementById('domain');
var city = document.getElementById('city');
var obj = document.getElementById('obj');
var describe = document.getElementById('describe');
var brandpower = document.getElementById('brandpower');
if (email.checkValidity() && first.checkValidity() && web.checkValidity() && city.checkValidity() && obj.checkValidity()) {
var emailV = email.value;
var firstV = first.value;
var webV = (web.value == undefined) ? 'null' : web.value;
var cityV = city.value;
var objV = obj.options[obj.selectedIndex].value;
var describeV = (describe && describe.options && describe.selectedIndex) ? describe.options[describe.selectedIndex].value : describe.value;
var brandpowerV = (brandpower && brandpower.options && brandpower.selectedIndex) ? brandpower.options[brandpower.selectedIndex].value : brandpower.value;
var radio = jQuery('input[name="dealer"]:checked').val();
jQuery.post("/form-one/?" + "email=" + emailV + "&first=" + firstV +
cityV + "&domain=" + webV + "&obj=" + objV + "&describe=" + describeV + "&brandpower=" + brandpowerV +
"&radio=" + radio, function () {
console.log("data sent");
})
.done(function () {
console.log("data success");
})
.fail(function () {
console.log("data failed");
})
.always(function () {
console.log("data finished");
email.value, first.value, web.value, city.value, obj.value, describe.value, brandpower.value = "";
//window.location.href = "/";
});
} else {
$('#error').css('display', 'block').delay(5000).queue(function (next) {
jQuery('#error').fadeOut('slow').css('display', 'none');
});
}
}
<button id="next" class="green-button" onClick="submitDataForm()">Next</button>
同样,我试图让表单除了提交数据(稍后将添加自定义事件)之外什么也不做,而不刷新或重新加载。
谢谢!
答案 0 :(得分:1)
event.preventDefault
确实有效。正如nnnnnn
指出的那样,你没有显示你尝试过的地方,但我怀疑你没有正确使用它,更有可能的是,你没有将event
传递给处理程序和e
或event
(无论你命名它)实际上是undefined
。以下是正确使用它的一种方法示例:
$('.ajax-submit').click(function(event) {
event.preventDefault();
console.log("button called");
//... all your other code here
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
<button id="next" class="green-button ajax-submit" > Next</button>
</form>