我通过AJAX向我的laravel应用程序发送store
请求。控制器功能正常工作,但我在ajax函数中无法获得成功消息,或者成功函数无效。
Ajax代码:
$.ajax({
type: "POST",
url: 'http://127.0.0.1:8000/dreams',
data: {
description: description,
offset_top: offset_top,
offset_left : offset_left
},
success: function(msg){
console.log("done");
}
});
Controller的store
功能:
public function store(Request $request)
{
echo $request;
if (Auth::check()) {
$user = Auth::user();
$dream = new Dream($request->all());
if ($dream) {
$user->dreams()->save($dream);
$response = array(
'dream' => $dream,
'status' => 'success',
'msg' => 'Setting created successfully',
);
return \Response::json($response);
}
return \Response::json(['msg' => 'No model']);
} else {
return \Response::json('msg' => 'no auth');
}
}
答案 0 :(得分:2)
尝试使用这种方式在ajax中传递数据。
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: 'http://127.0.0.1:8000/dreams',
data: {
description: description,
offset_top: offset_top,
offset_left: offset_left
},
success: function(msg) {
console.log("done");
}
});
答案 1 :(得分:0)
尝试使用以下代码存储方法:
public function store(Request $request)
{
if (Auth::check()) {
$user = Auth::user();
$dream = new Dream($request->all());
if ($dream) {
$user->dreams()->save($dream);
$response = array(
'dream' => $dream,
'status' => 'success',
'msg' => 'Setting created successfully',
);
return \Response::json($response);
}
return \Response::json(['msg' => 'No model']);
} else {
return \Response::json(['msg' => 'no auth']);
}
}
希望这对你有用!