[英]Can't submit form without reloading page
我建造了一個鏈接縮短器,只是為了好玩! 一切正常,但是每次我創建鏈接並提交表單時,頁面都會重新加載! 我想通過onclick="return false;"
來防止這種情況onclick="return false;"
但是沒有用。
<input class="submit" type="submit" value="Create!" />
$('#contactForm').submit(function () {
sendContactForm();
return false;
});
但是沒有任何效果,文件只是卡住了,什么也沒做! 我在做什么? 這是問題頁面https://viid.su PHP
require("db_config.php");
$uid = 1;
$flink = $_POST['url'];
if(!preg_match("/^[a-zA-Z]+[:\/\/]+[A-Za-z0-9\-_]+\\.+[A-Za-z0-9\.\/%&=\?\-_]+$/i", $flink)) {
$html = "Error: invalid URL";
} else {
$db = mysqli_connect($host, $username, $password);
$conn = new mysqli($host, $username, $password, $database);
$id = substr(md5(time().$flink), 0, 5);
if($conn->query("INSERT INTO `".$database."`.`link` (`id`, `flink`,`adonly`,`userid`) VALUES ('".$id."', '".$flink."','true','".$uid."');")) {
$html = 'Your short URL is <a class="test" href="https://viid.su/'.$id.'">https://viid.su/'.$id.'</a>';
} else {
$html = "Error: cannot find database";
}
mysqli_close($db);
}
您可以通過使用AJAX調用等方式提交表單而無需重新加載頁面。
的JavaScript
$('#contactForm').submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "path/to/your/script.php",
data: $('#contactForm').serialize(), // Packs the form's elements
success: function(data)
{
// Do something here if the call succeeded
alert(data);
}
});
}
的HTML
<form id="contactForm">
<input type="text" name="username" />
<input type="text" name="email" />
<input type="submit" value="Submit form" />
</form>
的PHP
<?php
echo $_POST['username'];
?>
遵循這些原則應該可以工作,並且您不需要其他任何東西,因為您已經在使用jQuery。
您需要使用事件對象作為函數回調中的參數並調用event.preventDefault()
只需將<input type="submit" />
更改為<input type="submit" />
<button onclick="return false;" id="shortenLinkButton">Send</button>
<button onclick="return false;" id="shortenLinkButton">Send</button>
然后,使用jQuery,您可以像這樣捕獲偶數:
// This code will be usable after the page has fully loaded
$(document).ready(function(){
// Catch the onclick event
$('#shortenLinkButton').on('click', function() {
// do something
alert('clicked the button, do your ajax stuff here after retrieving the data from the input');
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.