从表单上的PHP页面获取数据提交

时间:2013-08-27 14:41:44

标签: php jquery ajax forms get

我有一个表单的 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';
}

?>

4 个答案:

答案 0 :(得分:2)

你真的不需要“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>

答案 1 :(得分:1)

这是jquery Ajax示例,

  $.ajax({
        type: "POST",
        url: "somescript.php",
        datatype: "html",
        data: dataString,
        success: function(data) {
            doSomething(data);
        }
    });

答案 2 :(得分:0)

如何在index.php中执行此操作:

<div id="result"><?php include "process.php"?></div>

答案 3 :(得分:0)

两种方法。

使用ajax来调用你的process.php(我建议jQuery - 发送ajax调用并根据结果做事情很容易。)然后使用javascript来改变表单。< / p>

或者让创建表单的php代码与表单提交的php代码相同,然后根据是否有get参数输出不同的东西。 (编辑:MonkeyZeus为您提供了如何执行此操作的详细信息。)