2013-08-27 34 views
0

我有index.php一个表单。当它被提交时,我想从process.php的结果显示在index.php上的结果div内。肯定我需要某种形式的AJAX的,但我不知道......从表单提交的PHP页面获取数据

的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'; 
} 

?> 
+2

如果你对AJAX(这是它的方式)非常肯定,那么读一下它。谷歌'AJAX'至少:) – Alvaro

+0

你已经尝试过的AJAX?尝试使用AJAX,并告诉我们这个问题。 –

+0

[** Google展示div格式php **](https://www.google.ca/search?q=show+result+in+div+form+php&ie=utf-8&oe=utf-8&rls=org .mozilla:en-US:official&client = firefox -a&channel = np&source = hp&gws_rd = cr) –

回答

0

怎么样在这样做index.php:

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

1

这是jQuery的阿贾克斯例如,

$.ajax({ 
     type: "POST", 
     url: "somescript.php", 
     datatype: "html", 
     data: dataString, 
     success: function(data) { 
      doSomething(data); 
     } 
    }); 
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> 
+0

你有'if(isset($ _ POST ['submit'])){'那没用。我将它改为'if(isset($ _ GET ['submit'])){'现在它工作。 –

+0

你的'type:“POST,''很可能需要在你的Ajax方法中设置为'type:”GET“,''。 –

+0

哎呀,习惯的力量。很高兴它对你有效! – MonkeyZeus

0

两种方式来做到这一点。

要么使用ajax来调用你的process.php(我建议jQuery - 发送ajax调用和基于结果做东西是非常简单的),然后使用javascript来改变表单。

或者创建表单的php代码与表单提交的php代码相同,然后根据是否有get参数输出不同的东西。 (编辑:MonkeyZeus给了你如何做到这一点的具体细节。)