为什么安装 npm 后表单提交不起作用?



我创建了一个应用程序,使用 Laravel 6 分析博客中的帖子和海报。但是,由于某些原因,选择帖子或海报的表单提交不起作用。 我想问题是在我删除 npm 模块并安装另一个时间 npm 后开始的。

这是我的代码:

@extends('layouts.layout')
@section('content')
<form method="GET" id="poster_submit">
@csrf
<div class="form-group mt-5 col-sm-6 offset-sm-3">
<label for="select_poster" class="text-primary">Select a <b>Poster</b>:</label>
<div class="row">
<div class="col">
<select class="form-control" id="select_poster">
@foreach ($users as $user)
<option value="{{ $user->id }}">{{ $user->surname . " " . $user->firstname }}</option>
@endforeach
</select>
</div>
<div class="col">
<button type="submit" class="btn btn-primary btn-width">Go to the Poster!</button>
</div>
</div>
</div>
</form>
<form method="GET" id="post_submit">
@csrf
<div class="form-group col-sm-6 offset-sm-3 mt-5">
<label for="select_post" class="text-danger">Select a <b>Post</b>:</label>
<div class="row">
<div class="col">
<select class="form-control" id="select_post">
@foreach ($posts as $post)
<option value="{{ $post->id }}">{{ $post->id . " - " . $post->title }}</option>
@endforeach
</select>
</div>
<div class="col">
<button type="submit" class="btn btn-danger btn-width">Go to the Post!</button>
</div>
</div>
</div>
</form>
<script type="application/javascript">
$("#poster_submit").on("submit", function (e) {
e.preventDefault();
var poster_id = document.getElementById("select_poster");
var id = poster_id.options[poster_id.selectedIndex].value;
alert(id);
window.location = "profile/" + id;
});
$("#post_submit").on("submit", function (e) {
e.preventDefault();
var post_id = document.getElementById("select_post");
var id = post_id.options[post_id.selectedIndex].value;
alert(id);
window.location = "post/" + id;
});
</script>
@endsection

当我单击按钮时,没有任何反应,但我没有看到任何错误。我检查了JQuery是否正常工作。 当我单击一个按钮时,我应该会看到一个警报,然后我应该被重定向到另一个页面,但这不会发生,因为表单提交不起作用。 你知道吗?

在运行此代码之前,您应该确保加载了 jQuery。尝试用如下所示的其他代码包装它:

<script type="application/javascript">
$(function() {
$("#poster_submit").on("submit", function (e) {
e.preventDefault();
var poster_id = document.getElementById("select_poster");
var id = poster_id.options[poster_id.selectedIndex].value;
alert(id);
window.location = "profile/" + id;
});
$("#post_submit").on("submit", function (e) {
e.preventDefault();
var post_id = document.getElementById("select_post");
var id = post_id.options[post_id.selectedIndex].value;
alert(id);
window.location = "post/" + id;
});
});   
</script>

否则,请包含您的 JavaScript 控制台日志

既然你已经把

e.preventDefault()

在您的提交事件中,它将阻止表单提交。

基本上你可以做的是你可以删除e.preventDefault((并让表单提交到你的控制器的方法,并从方法中重定向到新的URL。

最新更新