2010-11-16 103 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()"

只是个开始。