为什么 Ajax post 会同时新建多条纪录?
我发现一个奇怪的现象,就是如果前端页面使用ajax的post函数在后端laravel使用
Model::create($request->all())
新建纪录时,会经常出现(不是每次都会)一次新建两条甚至有时候三条完全相同的纪录(这些纪录只有ID不一样,其他连时间戳都一样显示是同时新建的)的情况,即使我把代码改成firstOrCreate也不行:
$o = Model::firstOrCreate([
'key1' => $request->key1,
'key2' => $request->key2
]);
$o->value1 = $request->value1;
$o->save();
我查了一下stackoverflow
http://stackoverflow.com/questions/4263599...
有说js有提交2 requests的情况?
请问有谁知道为什么会出现这种情况?如何比较好的解决?
以下是前端js代码
$('.set-score').click(function () {
$(this).attr('disabled', true);
var id = $(this).attr('id').substr(10);
var score = $('select#select-score-' + id).children('option:selected').val();
var comment = $('input#edit-comment-' + id).val();
$.ajax({
url: '/teacher/score',
type: 'POST',
data: {
_token: '{{ csrf_token() }}',
answer_id: id,
score: score,
comment: comment,
teacher_id: '{{ Auth::guard('teacher')->user()->id }}'
},
success: function (data) {
score = JSON.parse(data);
$('span#score-' + id).text(score.score);
},
error: function (data) {
alert('Error! please try later!');
$(this).prop('disabled', false);
}
});
});
推荐文章: