[英]Why does form submission not work after an installation of 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 是否正常工作。 當我點擊一個按鈕時,我應該看到一個警告,然后我應該被重定向到另一個頁面,但這並沒有發生,因為表單提交不起作用。 你有什么想法嗎?
既然你已經把
e.preventDefault()
在您的提交事件中,它將阻止表單提交。
基本上你可以做的是你可以刪除 e.preventDefault() 並讓表單提交到控制器的方法,並從方法中重定向到新的 URL。
您應該確保在運行此代碼之前加載了 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 控制台日志
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.