2010-09-08 135 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