[英]not able to submit form without page reloading
我有以下代码,希望在不重新加载页面的情况下提交表单,但是它将重新加载整个页面,并且在控制台中检查script.php页面时也未执行。
index.php页面上的代码
<script>
$(function() {
$(".submit").click(function() {
var name = $("#name").val();
var dataString = 'name=' + name;
console.log(dataString);
$.ajax({
type: "POST",
url: "script.php",
data: dataString,
success: function() {
$('#result').html(response);
}
});
return false;
});
});
</script>
<form method="post" name="form">
<input id="name" name="name" type="text" />
<input type="submit" value="Submit" class="submit" />
</form>
<div id="result"></div>
script.php页面上的代码
<?php
$name=$_POST['name'];
echo $name;
?>
任何人都可以告诉我如何在不重新加载页面的情况下提交表单,并在index.php页面上显示script.php页面的结果
更新您的功能。 在函数中传递事件对象。 并使用event.preventDefault()阻止默认的提交操作。
$(".submit").click(function(e) {
e.preventDefault();
尝试这个
<script>
$(function() {
$(".submit").click(function(event) {
event.preventDefault();
var name = $("#name").val();
var dataString = 'name=' + name;
console.log(dataString);
$.ajax({
type: "POST",
url: "script.php",
data: dataString,
success: function() {
$('#result').html(response);
}
});
return false;
});
});
要么
<input type="button" class="submit" />Submit
不要混用表单submit
和按钮click
。
如果您是button
的click
事件,则使用type="button"
;如果您正在执行$("form").submit()
则使用type="submit"
。
同时检查
$(".submit").click(function(e) {
e.preventDefault();
并检查您的ajax
发布data
,
$.ajax({
type: "POST",
url: "script.php",
//changes made here
data: { name: $("#name").val()},
//changes made here. you have not written response
success: function(response) {
$('#result').html(response);
}
});
您需要将数据从script.php页面发送回index.php页面。 为此,将一点ajax切掉:
$.ajax({
type: "POST",
url: "script.php",
data: "datastring",
dataType: "json",
success: function(dataType){
$("#result").html(dataType);
}
});
在您的script.php中:
<?php
$name=$_POST['name'];
echo json_encode($name);
?>
与其监听输入的click
事件,不如监听表单的submit
。
<script>
$(function() {
$("#name-form").on('submit', function(e) {
e.preventDefault(); // prevent form submission
var name = $("#name").val();
var dataString = 'name=' + name;
console.log(dataString);
$.ajax({
type: "POST",
url: "script.php",
data: dataString,
success: function(response) {
$('#result').html(response);
}
});
});
});
</script>
<form id="name-form" method="post" name="form">
<input id="name" name="name" type="text" />
<input type="submit" value="Submit" class="submit" />
</form>
<div id="result"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.