我有一个从数据库加载的表。我希望每当用户输入记录时。记录应添加到表中,而不刷新整个页面。这应该在 AJAX 函数中。这是我的 JavaScript 代码:
$(document).ready(function(){
//save button listener
$("#save").click(function(){
//receiving data entered by user from design.php
var name = $('#name').val();
var email = $('#email').val();
var telephone = $('#telephone').val();
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
type:'POST',
url: 'contactData.php',
data:{"name":name,"telephone":telephone,"email":email, "username":username, "password":password},
// dataType:'json',
success: function(data) {
ssword);
var result = JSON.parse(data);
$("#validate").html(result.msg);
}
});//end of ajax
});//end of listener
});//end of javascript
这是我的表格(PHP):
<div class="table">
<?php
//connect to the database
$username="root";
$password="";
$host="localhost";
$connector = mysql_connect($host,$username,$password)
or die("Unable to connect");
$selected = mysql_select_db("mysql", $connector)
or die("Unable to connect");
//execute the SQL query and return records
$result = mysql_query("SELECT * FROM users ");
?>
<table border="2" style= "background-color: #99ffcc; color: #761a9b; margin: 0 auto;">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Telephone</th>
<th>Username</th>
<th>Password</th>
<tbody>
<?php
while( $row = mysql_fetch_assoc( $result ) )
{
echo "<tr>
<td>{$row['name']}</td>
<td>{$row['email']}</td>
<td>{$row['telephone']}</td>
<td>{$row['username']}</td>
<td>{$row['password']}</td>
</tr>\n";
}
?>
</tbody>
</tr>
</thead>
</table>
</div>
如何在AJAX函数中刷新表格?
最佳答案
向您的 tbody 添加一个类。
<tbody class="res-container">
在 AJAX 调用中,您可以尝试此操作。
data1: {name: name, telephone: telephone, email: email, username: username, password: password},
success: function(response) {
var html = '<tr>';
html = html + '<td>' + this.data1.name + '</td>';
html = html + '<td>' + this.data1.email + '</td>';
html = html + '<td>' + this.data1.telephone + '</td>';
html = html + '<td>' + this.data1.username + '</td>';
html = html + '<td>' + this.data1.password + '</td>';
html = html + '</tr>';
$('.res-container').append(html);
}
this.data1.name
基本上是访问 ajax data1 属性。因此,无论您在那里分配什么名称,这里都应该使用相同的名称。
更新:
我已修改代码以更新正确的值。我无法在成功中使用 this.data
。因此,我创建了另一个名为 data1
的属性,并使用 this.data1
来访问它。
关于javascript - 如何使用 AJAX 在点击保存时向表中添加记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24406150/