2010-11-16 140 views
0

的test.htmlphp-How to post with ajax?

<html> 
    <!-- 
    Please see the full php-ajax tutorial at http://www.php-learn-it.com/tutorials/starting_with_php_and_ajax.html 
    If you found this tutorial useful, i would apprciate a link back to this tutorial. 
    Visit http://www.php-learn-it.com for more php and ajax tutrials 
    --> 
    <title>php-learn-it.com - php ajax form submit</title> 
    <head>  
     <script type="text/javascript" src="prototype.js"></script> 
     <script> 

      function sendRequest() { 
       new Ajax.Request("test.php", 
        { 
        method: 'post', 
        postBody: 'name='+ $F('name'), 
        onComplete: showResponse 
        }); 
       } 

      function showResponse(req){ 
       $('show').innerHTML= req.responseText; 
      } 
     </script> 
    </head> 

    <body> 
     <form id="test" onSubmit="return false;"> 
      <input type="hidden" name="name" id="name" value="value"> 
      <input type="hidden" name="somethingElse" value="test" value="submit" onClick="sendRequest()"> 
     </form> 
     <a href="#" onclick="myForm.submit()">Post!</a> 

     <div id="show"></div> 
     <br/><br/> 

    </body> 

</html> 


<?php 
/* 
* Please see the full php-ajax tutorial at http://www.php-learn-it.com/tutorials/starting_with_php_and_ajax.html 
* If you found this tutorial useful, i would apprciate a link back to this tutorial. 
* Visit http://www.php-learn-it.com for more php and ajax tutrials 
*/ 

if($_POST["name"] == "") 
    echo "name is empty"; 
else 
    echo "you typed ".$_POST["name"]; 
?> 

哪裏是在form感謝錯了。

回答

3

有幾件事情是錯在這裏:

  1. 你一個隱藏的表單元素
  2. 崗位上有一個onclick!錨的onclick沒有提交任何

更改建議:

<head>  
    <script type="text/javascript" src="prototype.js"></script> 
    <script> 
     function showResponse(req){ 
      $('show').innerHTML = req.responseText; 
     } 
    </script> 
</head> 

<body> 
    <form id="test" name="test" action="test.php"> 
     <input type="hidden" name="name" id="name" value="cats" /> 
     <input type="hidden" name="somethingElse" value="test" /> 
    </form> 
    <a href="#" onclick="$('test').request({onComplete: showResponse})">Post!</a> 

    <div id="show"></div> 

</body> 
+0

謝謝。正確的方式。 – 2010-11-16 17:13:15

1

form id="test"和沒有名字

,但:

a href="#" onclick="myForm.submit()"

只是個開始。