0

我有一个带有表格的index.php 。当它被提交时,我希望process.php的结果显示在index.php的结果 div 中。很确定我需要某种 AJAX,但我不确定......

索引.php

<div id="result"></div>

<form action="" id="form" method="get">
    <input type="text" id="q" name="q" maxlength="16">
</form>

进程.php

<?php

$result = $_GET['q'];

if($result == "Pancakes") {
    echo 'Result is Pancakes';
}

else {
    echo 'Result is something else';
}

?>
4

4 回答 4

2

您真的不需要为此“需要” AJAX,因为您可以将其提交给自己并包含流程文件:

索引.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>

进程.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>
于 2013-08-27T14:46:42.063 回答
1

这是 jquery Ajax 示例,

  $.ajax({
        type: "POST",
        url: "somescript.php",
        datatype: "html",
        data: dataString,
        success: function(data) {
            doSomething(data);
        }
    });
于 2013-08-27T14:46:32.157 回答
0

有两种方法可以做到。

要么使用 ajax 调用你的 process.php(我推荐使用jQuery——发送 ajax 调用并根据结果执行操作非常容易。)然后使用 javascript 更改表单。

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

于 2013-08-27T14:47:14.070 回答
0

在您的 index.php 中执行此操作怎么样:

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

于 2013-08-27T14:45:44.933 回答