ajax在文本框中显示查询结果

时间:2013-01-16 20:28:00

标签: php ajax

好的,所以我在GoDaddy托管帐户上安装了jQuery。我需要在文本框中显示结果并完成我的HTML,它获取用户输入,按钮单击和结果区域(div id = status)。我想简单地将结果放在一个框中而不必刷新页面。我正在尝试这个json的东西和AJAX来完成这个,我试图弄清楚我的尝试有什么问题。这是HTML。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1  /DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<script language='JavaScript' type='text/javascript'>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>

</head>
<body>
<p>Miles <input name="miles" id="miles" type="text" /> <button type="button" name="getdata" id="getdata">Submit</button></p>
<p></p>
<div id="status">

</div>
<script type="text/javascript" language="javascript">
$('getdata').click(function(){

   $.ajax({
           url: 'process.php',
           type:'POST',
           dataType: 'json',
           success: function(output_string){
                   $('#result_table').append(output_string);
               }
           ));

});
</script>
</body>
</html>

它应该发送到process.php文件:

<?php
$hostname = 'myhost.com';
$username = 'ratetable';
$password = 'mypassword';

$miles = (int) $_POST['miles'];

try 
{
   $db = new PDO("mysql:host=$hostname;dbname=ratetable", $username, $password);

   foreach($db->query('SELECT * FROM rates WHERE mileage<= ' . $miles . ' ORDER BY mileage DESC LIMIT 1') as $row) {
   $output_string .= '<input type='text' name='answer' value='" . $row['ratepermile'] . "'>';

   }
}         
echo json_encode($output_string);
catch (PDOException $e) {
   echo $e->getMessage();
   throw($e);
}
?>

我尝试使用一个示例来构造它并且没有任何反应......甚至不是HTML表单。这有什么问题?

感谢您一看。

2 个答案:

答案 0 :(得分:1)

您的选择器错误$('getdata')应为$('#getdata'),您必须在id前加#来选择带有ID的元素。您还必须将参数传递给帖子请求

$.ajax({
       url: 'process.php',
       type:'POST',
       data: {miles: $('#miles').val()},
       dataType: 'json',
       success: function(output_string){
               $('#result_table').append(output_string);
       }
));

答案 1 :(得分:0)

试试这个,

$('#result_table').val(output_string);