这是我第一次尝试使用ajax。我成功地从表中检索数据,但我希望能够引入整个数据网格。我不完全确定如何做到这一点。
现在,我的index.php文件看起来像这样:
<html>
<head><title>Ajax Stuff</title>
</head>
<body>
<input id="username" name="username" type="text" />
<button type="submit" id="myBtn" name="myBtn">Submit</button>
<div id="name-data"></div> // <-data will be sent here
<script src="js/jquery-2.0.3.min.js"></script>
<script src="js/global.js"></script>
</body>
</html>
以下是global.js的代码:
$('#myBtn').on('click', function(){
var name = $('#username').val();
if($.trim(name) != '')
{
$.post('ajax/name.php', {username: name}, function(data){
$('#name-data').text(data);
});
}
});
最后,这是名为name.php的ajax文件的代码:
<?php
include("../include/database/php");
if(isset($_POST['username']) === true && empty($_POST['username']) === false)
{
$query = mysql_query("SELECT * FROM users WHERE username = '" . mysql_real_escape_string(trim($_POST['username'])) . "'");
$resnum = mysql_num_rows($query);
$row = mysql_fetch_assoc($query);
// I just added these next few line
echo "username: " . $row[username] . " ";
echo "full name: " . $row[fullname] . " ";
echo "emaill: " . $row[email] . " ";
echo "user level: " . $row[userlevel] . " ";
echo "division: " . $row[division] . " ";
echo "phone: " . $row[phone] . " ";
echo "created by: " . $row[created_by] . " ";
}
使用上面的PHP代码,我可以显示我请求的行。但是我尝试添加一个表(在name.php中),我的主文件index.php实际上显示了屏幕上表的代码。
每当我尝试在PHP文件中使用HTML代码时,它都会将HTML代码打印到屏幕上。
例如,我尝试使用这样的BR标签:
<?php
echo "username: " . $row[username] . "<br />";
?>
屏幕将打印出来:
username: johbea1234 <br />
当我尝试使用表标签时也是如此。
我该如何解决这个问题?
请帮忙。
答案 0 :(得分:1)
更改
$('#name-data').text(data);
到
$('#name-data').html(data);
然后您可以使用任何您喜欢的HTML标签。
另外
<div id="name-data"></div> // <-data will be sent here
不太正确,更像是:
<div id="name-data"><!-- data will be sent here --></div>
但您可能已经知道,并且只是为可能正在阅读您问题的人添加了评论。
答案 1 :(得分:0)
为''
添加username
。
更改
$.post('ajax/name.php', {username: name}, function(data){.....
到
$.post('ajax/name.php', {'username': name}, function(data){.....