PHP:如何在没有表单回发的情况下执行查询?
我有一个表单,我想在其中进行验证。但是有一个字段,我想在编写查询时验证它。我不希望表单回发,因为回发后表单中填写的所有值都将丢失。有没有办法不回发就编写查询,或者如果必须回发,如何保留这些值?请提供帮助如果您使用AJAX(jQuery),您可以在不刷新浏览器的情况下发布XML请求,如果您需要的话。 为此,只需创建一个包含一些文本字段和提交按钮的表单,为所有内容提供一个ID,并为按钮添加一个单击侦听器:PHP:如何在没有表单回发的情况下执行查询?,php,ajax,Php,Ajax,我有一个表单,我想在其中进行验证。但是有一个字段,我想在编写查询时验证它。我不希望表单回发,因为回发后表单中填写的所有值都将丢失。有没有办法不回发就编写查询,或者如果必须回发,如何保留这些值?请提供帮助如果您使用AJAX(jQuery),您可以在不刷新浏览器的情况下发布XML请求,如果您需要的话。 为此,只需创建一个包含一些文本字段和提交按钮的表单,为所有内容提供一个ID,并为按钮添加一个单击侦听器: $('#submit-button').click(function() { var
$('#submit-button').click(function() {
var name = $('#username').val();
$.ajax({
type: 'POST',
url: 'php_file_to_execute.php',
data: {username: name},
success: function(data) {
if(data == "1") {
document.write("Success");
} else {
document.write("Something went wrong");
}
}
});
});
如果用户单击带有“提交按钮”-ID的按钮,则调用此函数。然后使用POST将文本字段的值发送到php_文件_to_execute.php。在这个.php文件中,您可以验证用户名并输出结果:
if($_POST['username'] != "Neha Raje") {
echo "0";
} else {
echo "1";
}
我希望我能帮助你!:) 你可能想重新措辞你写的东西,它有点不清楚。仅供参考,我是这样做的
<form method="post">
Text 1: <input type="text" name="form[text1]" value="<?=$form["text1"]?>" size="5" /><br />
Text 2: <input type="text" name="form[text2]" value="<?=$form["text2"]?>" size="5" /><br />
<input type="submit" name="submit" value="Post Data" />
</form>
<?php
if ($_POST["submit"]) {
$i = $_POST["form"];
if ($i["text1"] or ..... ) { $error = "Something is wrong."; }
if ($i["text2"] and ..... ) { $error = "Maybe right."; }
if (!$error) {
/*
* We should do something here, but if you don't want to return to the same
* form, you should definitely post a header() or something like that here.
*/
header ("Location: /"); exit;
}
//
}
if (!$_POST["form"] and !$_GET["id"]) {
} else {
$form = $_POST["form"];
}
?>
文本1:使用jQuery的$.post()
方法如下:
$('#my_submit_button').click(function(event){
event.preventDefault();
var username = $('#username').val();
$.post('validate.php', {username: username, my_submit_button: 1}, function(response){
console.log(response); //response contain either "true" or "false" bool value
});
});
在validate.php中,从表单异步获取用户名,如下所示:
if(isset($_POST['my_submit_button']) && $_POST['my_submit_button'] == 1 && isset($_POST['username']) && $_POST['username'] != "") {
// now here you can check your validations with $_POST['username']
// after checking validations, return or echo appropriate boolean value like:
// if(some-condition) echo true;
// else echo false;
}
<>强>注释:在使用Ajax执行数据库更改脚本之前,请考虑了解与安全相关的漏洞和其他问题。当你说“回发”时,你的意思是什么?