[英]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.