2010-09-08 56 views
5

我一直在試圖創建一個簡單的計算器。使用PHP,我設法從POST的輸入字段和跳轉菜單中獲取值,但是當提交時刷新表單。最簡單的方法,使表單提交無刷新

使用JavaScript我嘗試使用

function changeText(){ 
document.getElementById('result').innerHTML = '<?php echo "$result";?>' 

但這將繼續點擊按鈕後給人的「0」的答案,因爲作爲表單沒有提交它不能從POST得到的值。

所以我試圖找出兩種最簡單的方法是通過AJAX或類似

事做,或得到所選值跳轉菜單是用JavaScript。

我已經閱讀了一些Ajax在線的例子,但它們是相當混亂(不熟悉的語言)

+0

閱讀我的文章,然後看看jQuery,它非常適合初學者 – RobertPitt 2010-09-08 10:59:20

回答

7

使用jQuery + JSON組合提交表單是這樣的:

test.php的:

<script type="text/javascript" src="jquery-1.4.2.js"></script> 
<script type="text/javascript" src="jsFile.js"></script> 

<form action='_test.php' method='post' class='ajaxform'> 
<input type='text' name='txt' value='Test Text'> 
<input type='submit' value='submit'> 
</form> 

<div id='testDiv'>Result comes here..</div> 

_test.php:

<?php 
     $arr = array('testDiv' => $_POST['txt']); 
     echo json_encode($arr); 
?> 

jsFile.js

jQuery(document).ready(function(){ 

    jQuery('.ajaxform').submit(function() { 

     $.ajax({ 
      url  : $(this).attr('action'), 
      type : $(this).attr('method'), 
      dataType: 'json', 
      data : $(this).serialize(), 
      success : function(data) { 
         for(var id in data) { 
          jQuery('#' + id).html(data[id]); 
         } 
         } 
     }); 

     return false; 
    }); 

}); 
+0

我現在已經工作了,謝謝大家! – James 2010-09-08 13:05:45

7

做,這是使用Ajax和jQuery

你有後包括你的jQuery的最佳方式圖書館在你的腦海中,使用類似於下面的東西

$('#someForm').submit(function(){ 
    var form = $(this); 

    var serialized = form.serialize(); 

    $.post('ajax/register.php',{payload:serialized},function(response){ 
     //response is the result from the server. 
     if(response) 
     { 
      //Place the response after the form and remove the form. 
      form.after(response).remove(); 
     } 
    }); 
    //Return false to prevent the page from changing. 
    return false; 
}); 

你的PHP會是這樣的。

<?php 
    if($_POST) 
    { 
     /* 
      Process data... 
     */ 


     if($registration_ok) 
     { 
      echo '<div class="success">Thankyou</a>'; 
      die(); 
     } 
    } 
?> 
+0

謝謝,生病給我一個去 – James 2010-09-08 10:59:55

+4

+1,很好的解釋。如果你想要一個更懶惰的辦法,在[jQuery的形式插件(http://jquery.malsup.com/form/)是很好的。它甚至可以處理文件上傳,而傳統的Ajax不能。 – 2010-09-08 11:00:33

+0

虐待同意該插件,將幫助他開始。 – RobertPitt 2010-09-08 11:47:45

0

我用一個新的窗口。在保存時,我打開一個處理保存並關閉onload的新窗口。

window.open('save.php?value=' + document.editor.edit1.value, 'Saving...','status,width=200,height=200'); 

該php文件將包含一個bodytag與onload =「window.close();」並在此之前,PHP腳本來保存我的編輯器的內容。

它可能不是很安全,但你要求其簡單。編輯得到保留其撤消信息等

+0

,並且如果用戶阻止了彈出窗口,則會被擰緊。 – Skuta 2013-07-07 13:48:29