获取数据并使用ajax在文本框中显示它

时间:2014-01-31 19:55:50

标签: javascript php mysql ajax

正如你可以看到我当前的代码不起作用,我需要你的帮助...我想在我的搜索(文本框)中过滤并显示在那里过滤相应文本框的数据...任何人都可以帮助我的代码工作??我一直在谷歌寻找几个小时已经有同样的想法,我的程序有效,但我找不到任何帮助我请。

示例预期输出:

enter image description here

html代码:

<form method="post">
Search batchcode: <input type="text" id="query" /><br />
<table>
<tr>
<td>
ID: <br />
<input id="result" type="text" name="id1" /> <br />
<input id="result" type="text" name="id2" /> <br />
</td>
<td>
Name: <br />
<input id="result" type="text" name="name1" /> <br />
<input id="result" type="text" name="name2" /> <br />
</td>
<td>
Score 1: <br />
<input id="result" type="text" name="optA1" /> <br />
<input id="result" type="text" name="optA2" /> <br />
</td>
<td>
Score 2: <br />
<input id="result" type="text" name="optB1" /> <br />
<input id="result" type="text" name="optB2" /> <br />
</td>
<td>
Other Qualification: <br />
<input id="result" type="text" name="other_qual1" /> <br />
<input id="result" type="text" name="other_qual2" /> <br />
</td>
<td>
Interview: <br />
<input id="result" type="text" name="interview1" /> <br />
<input id="result" type="text" name="interview2" /> <br />
</td>
<td>
Total: <br />
<input id="result" type="text" name="total1" /> <br />
<input id="result" type="text" name="total2" /> <br />
</td>
</tr>
</table>
</form>

脚本功能:

<script type="text/javascript">
$(document).ready(function(){

$('input[name^=search]').click(function(e){
e.preventDefault(); 
$.ajax({
url:"search.php",
type:"POST",
data : { term : $('#query').val() },
dataType:json,
success : function(result) {
alert(result);
            }
        });
    })
});      
</script>

search.php页面:

<?php

$q = $_GET['term'];

mysql_connect("localhost","root","");
mysql_select_db("test");
$query = mysql_query("SELECT * FROM score WHERE batchcode LIKE '$q%'");

$data = array();
while($row = mysql_fetch_array($query)){
$data[]=array('value'=>$row['batchcode']);
        $id[] = $row['id'];
        $name[] = $row['name'];
        $score1[] = $row['score1'];
        $score2[] = $row['score2'];
        $other_qual[] = $row['other_qual'];
        $interview[] = $row['interview'];
        $total[] = $row['total'];
}
echo json_encode($data);
?>

2 个答案:

答案 0 :(得分:0)

在回显结果之前,你应该在php文件中添加它:

header('Content-type: application/json');

并在文本框中显示数据我会做类似的事情:

$("#element").val(result.value);

正如其他人在评论中指出的那样,你绝对应该使用PDO或mysqli从数据库中获取数据。

答案 1 :(得分:0)

没有任何“搜索”按钮来单击处理程序。 尝试在搜索输入后添加按钮,如下所示:

Search batchcode: <input type="text" id="query" /><br />
<input type="button" id="search" value="Search"/>