当我使用AJAX通过PHP编辑SQL数据库时,我遇到了问题。它有效,但您必须单击“删除”按钮,刷新页面以查看它没有工作,然后再次执行完全相同的操作,或者有时只需等待几秒钟再重新加载页面。这看起来很奇怪。
这是我的HTML和JS
<html>
<script type="text/javascript">
$("#placeTable").on('click', 'button.remove', function(e){
var targ = e.target;
var id = $(targ).attr('data-id');
bootbox.confirm("Are you sure you want to remove?", function(result) {
if (result == true) {
$.post('/removelocation', {lid : id}, function(){
$(targ).closest('tr').remove();
})
}
})
})
</script>
<table id="placeTable" class="table table-hover table-condensed">
<tr>
<th>Date</th>
<th>Place</th>
<th>Comments</th>
<th>Actions</th>
</tr>
{% for locat in location %}
<tr>
<td data-id="{{locat.getID}}">{{locat.date}}<br/>{{locat.time}}</td>
<td data-id="{{locat.getID}}">{{locat.name}}</td>
<td data-id="{{locat.getID}}">{{locat.description}}</td>
<td>
<button data-id="{{locat.getID}}" class="remove btn btn-link"><i class="icon-remove"></i></button>
<button data-id="{{locat.getID}}" class="edit btn btn-link"><i class="icon-edit"></i></button>
</td>
</tr>
{% endfor %}
</table>
<div id="editmodal" class="modal hide fade">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<form class="form-vertical" action="" method="POST">
<div class="joshPad">
<fieldset>
<label for="logPlaceChange">Place Name</label>
<input type="text" id="logPlaceChange" name="logPlaceChange"></input>
<label for="logPlaceDescriptionChange">Comments</label>
<textarea rows="3" id="logPlaceDescriptionChange" name="logPlaceDescriptionChange"></textarea>
<label class="checkbox">
<input type="checkbox" name="logCurrentPlace"> Use my location</input>
</label>
</fieldset>
</div>
</form>
</div>
<div class="modal-footer">
<a href="#" class="btn" data-dismiss="modal" aria-hidden="true">Close</a>
<a href="#" class="btn changeSubmit">Save changes</a>
</div>
</div>
</html>
这是我的PHP
<?php
case 'removelocation' :
R::trash(R::load('location', $_POST['lid']));
//I HAVE ALSO TRIED THIS TO TRASH ELEMENT AND BEFORE USING AJAX WHEN USING A SIMPLE POST FORM BOTH WORK FOR ME;
$locationID = $_POST['lid'];
$locat = R::load('location', $locationID);
$usery = R::load('user', $_SESSION['user']->getID());
R::trash($locat);
R::dependencies(array('location'=>array('user')));
unset($usery->ownLocation[$locationID]);
R::store($usery);
exit;
?>
任何帮助,找出它为什么不能正常工作将非常感激。感谢
答案 0 :(得分:0)
我认为最接近的函数可能指向不同的选择器,我不知道您使用哪个PHP或JS工具来呈现表数据,但是一个好主意是将JS代码封装到map中在jQuery映射其click函数之前,如果你的按钮没有被加载,则处于文档就绪状态。
var xhttp = new XMLHttpRequest();
xhttp.open("GET", window.parent.INDEX_URL, false);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send();
var response = JSON.parse(xhttp.responseText);
console.log("response",response);