2013-08-27 35 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給了你如何做到這一點的具體細節。)