[英]Getting data from PHP page on form submit
我有带表格的index.php 。 提交后,我希望process.php的结果显示在index.php的结果div中。 可以肯定,我需要某种AJAX,但不确定...
index.php
<div id="result"></div>
<form action="" id="form" method="get">
<input type="text" id="q" name="q" maxlength="16">
</form>
process.php
<?php
$result = $_GET['q'];
if($result == "Pancakes") {
echo 'Result is Pancakes';
}
else {
echo 'Result is something else';
}
?>
您确实不需要“ AJAX”,因为您可以将其提交给自己并包含过程文件:
index.php
<div id="result">
<?php include('process.php'); ?>
</div>
<form action="index.php" id="form" method="get">
<input type="text" id="q" name="q" maxlength="16">
<input type="submit" name="submit" value="Submit">
</form>
process.php
<?php
// Check if form was submitted
if(isset($_GET['submit'])){
$result = $_GET['q'];
if($result == "Pancakes") {
echo 'Result is Pancakes';
}
else {
echo 'Result is something else';
}
}
?>
实现AJAX将使事情变得更加用户友好,但这肯定会使您的代码复杂化。 无论走什么路都好运!
这是一个jQuery Ajax示例,
<script>
//wait for page load to initialize script
$(document).ready(function(){
//listen for form submission
$('form').on('submit', function(e){
//prevent form from submitting and leaving page
e.preventDefault();
// AJAX goodness!
$.ajax({
type: "GET", //type of submit
cache: false, //important or else you might get wrong data returned to you
url: "process.php", //destination
datatype: "html", //expected data format from process.php
data: $('form').serialize(), //target your form's data and serialize for a POST
success: function(data) { // data is the var which holds the output of your process.php
// locate the div with #result and fill it with returned data from process.php
$('#result').html(data);
}
});
});
});
</script>
这是jquery Ajax的例子,
$.ajax({
type: "POST",
url: "somescript.php",
datatype: "html",
data: dataString,
success: function(data) {
doSomething(data);
}
});
如何在您的index.php中执行此操作:
<div id="result"><?php include "process.php"?></div>
有两种方法。
要么使用ajax来调用您的process.php(我建议使用jQuery ,这很容易发送ajax调用并根据结果进行处理。)然后使用javascript来更改表格。
或者让创建表单的php代码与表单提交的php代码相同,然后根据是否有get参数输出不同的内容。 (编辑:MonkeyZeus为您提供了有关执行此操作的详细信息。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.