學習的目的,我創建了一個簡單的應用程序,基本上通過$.post
增加值到數據庫,並返回在同一時間使用JSON更新的結果。添加和更新不復制空元素 - jQuery的/ PHP
最大的問題是,增加和更新時,與空元素更新。例如:如果我已經添加了5個項目,那麼當添加一個項目時,它將刷新並返回5個已經有的項目,外加5個空項目和一個項目到發送值的末尾。
下面是jQuery的發送的代碼:
send_btn.bind('click', function() {
var that = $(this),
input_val = input_word.find('input').val();
that.find('.wrp').css('margin-left', -152);
$.post('post.php', { palavra: input_val }, function (data) {
console.log(data);
that.find('.wrp').css('margin-left', 0);
update();
});
});
下面是接收信息的PHP的文件:post.php
$_palavra = $_POST['palavra'];
$query = mysql_query("INSERT INTO `glaubersampaio`.`postit` (`ID`, `PALAVRA`, `MOSTRAR`) VALUES (NULL, '".$_palavra."', '1');");
update()
功能:
function update() {
$.getJSON('request.php', function (data) {
for (i = 0; i < data.length; i++) {
$('<li class="postit" id="postit-' + data[i].id + '"></li>').appendTo(quadro.find('ul'));
$('#postit-' + data[i].id).html('<h4>' + data[i].palavra + '</h4>');
$('<div class="remover">REMOVER?</div>').appendTo('#postit-' + data[i].id);
}
})
.done(function() {
quadro.find('.loader').hide();
});
}
的PHP請求文件:request.php
$query = mysql_query("SELECT * FROM `postit`");
$dados = array();
while($a = mysql_fetch_array($query)) {
$ID = $a['ID'];
$PALAVRA = $a['PALAVRA'];
$MOSTRAR = $a['MOSTRAR'];
array_push($dados, array("id"=>$ID, "palavra"=>$PALAVRA, "mostrar"=>$MOSTRAR));
}
echo json_encode($dados);