PHP / AJAX初学者需要帮助

时间:2010-10-22 17:24:26

标签: php javascript ajax

我想要做的是在PHP中输入字段的基本HTML表单,以便您可以用数据填充这些字段并将它们提交到数据库。一旦数据存在于数据库中,我希望该数据填充输入字段。我希望所有这些都在java / ajax / php中完成,所以我的页面永远不会刷新。但我可以将数据提交到MYSQL数据库并从中检索。

这样的示例代码是最好的,所以我可以看到并学习它。

现在我已经看到了如何从数据库中提取并在没有页面刷新的情况下使用数据填充输入。我还看到了如何在没有页面刷新的情况下将数据输入数据库。

我找不到两者结合的例子。

2 个答案:

答案 0 :(得分:1)

<form onsubmit="retrieve_data(...); return false;">
 <input type="text" name="foo" id="foo"/>
 <input type="submit"/>
</form>
<div id="ajax"></div>
<script>
 function retrieve_data(...) { ... }
 function update_form(...) { ... }
</script>

retrieve_data应该调用php脚本将数据存储到DB中,并将一些内容输出到div id="ajax"。但是如果你添加一些脚本,它就不会被执行:它需要一些事件才能运行。因此,我建议你的php脚本填充div id="ajax"

<img src="..." width="0" onload="update_form()"/>

你唯一需要的是编写函数retrieve_data(调用php脚本将内容返回到ajax div)和update_form,它们会更新你的表单字段。您的页面应该更新而不刷新。我希望它有所帮助。

答案 1 :(得分:1)

嗯,你有点像一次要求一切!

首先,您可能最好使用jQuery来简化Ajax请求。

让我们设置一个示例数据库。打开mysql命令行客户端,然后输入

mysql# create database test;
mysql# use test;
mysql# create table testpage(id int auto_increment,someval int,otherval varchar(16),primary key(id));

这是一个示例HTML页面。将其保存在您的Web根目录中test.php:

 <html>
  <head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
    <script>
      $(document).ready(function(){
        $('#senddata').click(function(){
            var an_int=parseInt($('#an_int').val(),10); //reads the content of the form inputs
            var a_string=$('#a_string').val();
            $.post('process.php',{"an_int":an_int,"a_string":a_string},function(data){
              if(data.result=='error'){ $('#status').text('An error occurred sending the data'); return false; }
              $('#show_int').text(data.stored_int);
              $('#show_string').text(data.stored_string);
              $('#status').text('Stored and displayed data successfully');
              })
            });
        });
    </script>
  </head>
  </body>
    <form>
      An integer: <input type='text' length='40' id='an_int'><br>
      A word: <input type='text' length='40' id='a_string'><br>
      <div id='senddata'>Send Data</div>
    </form>
    <br>
    <div id='status'>Enter data and click send to store and update.</div>
    <br>
    The Int: <div id='show_int'></div>
    The String: <div id='show_string'></div>
  </body>
</html>

好的,那么PHP。将其保存为process.php

<?php

$sent_string=preg_replace('#[^\w\d]#','',$_POST['a_string']); //will remove anything other than letters, _ and digits
$sent_int=(int)$_POST['an_int']; //will strip out any non digits, or set to 0 if not numeric at all

function pdo_connect($dbn='test')
{//connect, return a pdo connection object thing handle
try
  {
  $host='localhost';
  $user='root';
  $passw='yourpassword';
  $driver_opts = array( PDO::MYSQL_ATTR_INIT_COMMAND => 'set names utf8' );

  $db=new PDO("mysql:host=$host;dbname=$dbn",$user, $passw, $driver_opts);
  $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  }
catch(PDOException $err)
  {echo('Could not connect to database '.$dbn.' due to error: '.$err);return false;}

return $db;
}
$db=pdo_connect();
if(!$db){ exit; }

$sql='insert into testpage values(null,?,?)';
$insert_statement=$db->prepare($sql);

$data=array($sent_int,$sent_string);
$success=$insert_statement->execute($data);

$result=$success ? 'success' : 'error';

$result_array=array('result'=>$result,'stored_int'=>$sent_int,'stored_string'=>$sent_string);

header('Content-Type: application/json');
echo json_encode($result_array);
exit;

它并没有真正从数据库中读取信息,它只是返回它刚输入的内容。制作一个页面显示到目前为止输入的数据列表留给读者练习!希望这会有所帮助。

相关问题