Laravel 5.4:使用Ajax进行就地编辑 [英] Laravel 5.4: In-Place Editing with Ajax
问题描述
我当前拥有的页面显示了一个表,该表可动态生成显示用户信息的行.每行都有一个编辑"按钮,当单击该按钮时,会将相应的单元格转换为输入,然后将编辑"按钮转换为保存"按钮.单击该按钮后,该用户行的输入值应存储到数据库中.
The page I currently have shows a table that dynamically generates rows showing user information. Each row has an Edit button that, when clicked, turns the respective cells into inputs, and turns the Edit button into a Save button. When that button's clicked, the input values for that user's row should be stored into the database.
我当然没有太多的Ajax经验,但是我一直在网上寻找,我相信我正在遵循通过Ajax调用正确地调用Controller函数的一般过程.但是,当我尝试对其进行测试时,仍然出现500错误.我相信这可能取决于我如何获取请求并发回响应,但是我不确定具体错误.
I admittedly don't have a lot of experience with Ajax, but I've been looking online and I do believe I'm following the general procedure for calling a Controller function through an Ajax call properly. However, I'm still getting a 500 error when I try to test it. I believe it may be in how I am obtaining the request and sending back the response, but I'm unsure of the specific error.
我的代码包含以下内容:
My code contains as follows:
home.blade.php
....
@foreach($users as $user)
<tr id="row{{ loop->iteration }}>
<input type='text' id='first_name_input_row{{ loop->iteration }}'>
<input type='text' id='last_name_input_row{{ loop->iteration }}'>
<input type="button" id="save_button_row{{ $loop->iteration }}" class="btn btn-btn-submit" value="Save" class="save" onclick="save_row('{{ $loop->iteration }}', {{ $user }})">
</tr>
@endforeach
....
<script>
function save_row(num, user)
{
var id = 'row' + num;
$.ajax({
method: 'post',
url: '/update-table',
data: {
'_token': $('input[name=_token]').val(),
'first_name': $('input[id=first_name_input_' + id + ']').val(),
'last_name': $('input[id=last_name_input_' + id + ']').val(),
'user': user
},
success: function(response){
console.log("It worked!");
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("It failed!");
console.log(jqXHR);
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
</script>
HomeController.php
public function updateTable(Users $users){
$user = request()->input('employee');
$first_name = request()->input('first_name');
$last_name = request()->input('last_name');
$users->editUser($user, $first_name, $last_name);
return response()->json($user);
}
Users.php
public function editUser($user, $first_name, $last_name) {
$user->first_name = $first_name;
$user->last_name = $last_name;
$user->save();
}
推荐答案
我最终设法弄清了这个问题,这是由于我的某些变量中存在简单的拼写错误.我有点后悔像我一样匆忙地提出这个问题,我为此道歉,因为基本上让它像我一样久.
I eventually managed to figure out the issue with this, which was due to simple typos in some of my variables. I somewhat regret making this question as hastily as I did, and I do apologize for basically letting this sit as long as I did:
If anyone's interested, a sort of "follow-up" question to this piece can be found here
这篇关于Laravel 5.4:使用Ajax进行就地编辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!