Skip to content

Instantly share code, notes, and snippets.

@yankchina
Last active June 25, 2016 12:08
Show Gist options
  • Save yankchina/90ce286ae5ec73511a8a080f373fa042 to your computer and use it in GitHub Desktop.
Save yankchina/90ce286ae5ec73511a8a080f373fa042 to your computer and use it in GitHub Desktop.
用 laravel 5 框架做后台 + bootstrap(Modal)窗体做前台,Ajax 更改数据库表数据的方法
jQuery(document).ready(function() {
$('#edit').on('show.bs.modal', function (e) {
$id = e.relatedTarget.id; // 从触发按钮上获取到 id 号
// Ajax 获取数据,并且填充到表单中
$url = "/comment/api/one?id="+$id;
$.ajax({
type: "get",
url: $url,
dataType: 'json',
success : function(data){
if(data.length > 0){
$('#id_').val($id);
$('#author').val(data[0].author);
$('#content').val(data[0].content);
}
}
});//ajax
});//show.bs.modal
$('button#form-submit').on('click',function(e){
$id = $('#id_').val();
$author = $('#author').val();
$content = $('#content').val();
$status_code = $('#status_code').val();
$url = "/comment/api/modify",
$.ajax({
type: "post",
url: $url,
data: { 'id': $id,'author' : $author, 'content' : $content, 'status_code': $status_code},
dataType: 'json',
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
},
success: function(data){
console.log(data.status);
window.location.reload(true); // 重新刷新一下页面
},
error: function(xhr, type){
console.log('Ajax error!')
}
});
$('#edit').modal('hide');
});
});
@yankchina
Copy link
Author

  1. 在点开table中的某行按钮,触发一个modal窗体
  2. modal窗体出现的时候,从触发按钮上获得该行元素的id号
  3. ajax get 方式获取远端的数据,填充到表单中
  4. 编辑完成后用 ajax post 方式推送给远端
  5. 注意laravel5的 CSRF机制,以及在传输Ajax成功后需要重新刷新页面。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment