我尝试使用 ajax 和 jquery validate() 函数提交表单。当我在本地测试它时, event.preventDefault() 有效!也没有“event.preventDefault();”行但是,当我将其部署到服务器时,结果 json 会加载到新页面中 - 它不会阻止重定向。
$(function () {
$("#photo-form").validate({
submitHandler: function (form, event) {
event.preventDefault(); //with or without - doesn't work
if ($(form)[0].checkValidity()) {
console.log("No Errors!")
var formData = new FormData(document.querySelector("#photo-form"));
var photo = formData.get("photo");
$.ajax({
url: "/photo/",
type: 'POST',
data: formData,
async: false,
success: function (data) {
console.log("Ajax success");
if (data.error == "OK") {
alert("Photo was uploaded");
} else {
//error
}
},
error: function (data) {
},
cache: false,
contentType: false,
processData: false
});
return false; //this also doesn't help
}
}
});
});
本例中错误出在哪里?这段代码的本地和服务器有什么区别?
HTML 表单:
<form id="photo-form" action="/photo/" method="post" enctype="multipart/form-data"
class="row col s10 center-block">
<div class="card row">
<div class="col s12">
<h5>Generic Information</h5>
<div class="input-field col s12 m6">
<i class="material-icons prefix">title</i>
<input id="campaign_id" type="text" name="campaign_id" class="validate" required>
<label for="campaign_id" data-error="huh?" data-success="WOW!">campaign_id</label>
</div>
<div class="input-field col s12 m6">
<div class="file-field input-field">
<button class="btn btn-floating pink lighten-1 file-btn">
<span>Photo</span>
<input name="photo" type="file">
</button>
<div class="file-path-wrapper">
<input class="file-path validate" type="text">
</div>
</div>
</div>
<div class="row">
<div class="input-field col s8">
<button class="btn-large waves-effect waves-light" type="submit">Submit
<i class="material-icons right">send</i>
</button>
</div>
</div>
</div>
</div>
</form>
最佳答案
这可能是因为您尝试使用 HTTP 加载 jquery 库,而您的 session 使用 HTTPS。确保您使用 https://
加载 jquery关于javascript - Form validate PreventDefault 仅在本地有效,在服务器上无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40438968/