我正在尝试使用 jquery 和 ajax 在 mysql 数据库中写入一些数据。查询成功,但我无法将数据附加到 div 数组中。
编辑:
$(document).ready(function(){
$("#sub").click( function() {
$.ajax({
type: "POST",
url: "insert.php",
dataType: 'json',
data: $("#myForm :input").serializeArray(),
success: function(data) {
data = $.parseJSON(data);
$("#data").append("<div class=\"row\">"
+data.position+" " //this section must be changed to
+data.text+" " // something but I dont know what
+data.id+" "
+data.date_added+" "
+"</div>");
},
error:function (xhr, ajaxOptions, thrownError){
$("#error").html(thrownError);
}
})
return false;
});
//disable form redirection
$("#myForm").submit( function() {
return false;
});
//clear input fields
function clearInput() {
$("#myForm :input").each( function() {
$(data).val('');
});
}
update();
});
function update() {
$.ajax({
type: "POST",
url: "fetch.php",
dataType: 'json',
success: function(data) {
$.each(data, function(){
$("#data").append("<div class=\"row\">"
+this['position']+" "
+this['text']+" "
+this['id']+" "
+this['date_added']+" "+
"</div>");
})
},
error:function (xhr, ajaxOptions, thrownError){
$("#error").html(thrownError);
}
});
return false;
};
我将如何显示查询成功后发布的数据?
编辑:
<body>
<div class="navbar navbar-inverse">
<div class="navbar-inner noRadius">
<a class="brand" href="#">toDo</a>
<ul class="nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">Home</a></li>
</ul>
</div>
</div>
<div id="main" class="container">
<div id="data"> </div>
<form id="myForm" action="insert.php" method="post">
Task: <input class="input-large" type="text" name="text" />
<br />
<button class="btn" id="sub">Save</button>
</form>
<span id="error"></span>
</div>
<!-- Including our scripts -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script type="text/javascript" src="script.js"></script>
<link href="library/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="library/js/bootstrap.min.js"></script>
<!--<script src="library/js/ajaxy.js"></script>-->
</body>
获取.php
<?php
include_once('db.php');
$sql = mysql_query("SELECT * FROM todo");
$tasks = array();
while( $row = mysql_fetch_assoc($sql) ){
$tasks[] = $row;
}
echo json_encode($tasks);
?>
插入.php
<?php
include_once('db.php');
$text = $_POST['text'];
$query=mysql_query("INSERT INTO todo(text) VALUES('$text')");
if($query){
echo "Data for $text inserted successfully!";
}
else{
echo "An error occurred!";
}
?>
我正在尝试构建一个简单的待办事项应用程序。
我更新了 insert.php,因为我打算使用 select 将数据插入到数据库中。我是初学者,我正在努力!请帮我解开!