如何返回保存到数据库中的注释,以便在.done()函数中使用它,这样我可以在不刷新页面的情况下显示该注释?
CommentController:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Comment;
class CommentsController extends Controller
{
public function postComment(Request $request){
$userId = $request['userId'];
$imageId = $request['imageId'];
$commentText = $request['comment'];
$comment = new Comment();
$comment->user_id = $userId;
$comment->image_id = $imageId;
$comment->comment = $commentText;
$comment->save();
}
}
JavaScript的:
$('.postComment').on('click', function(event){
event.preventDefault();
var userId = $("input[name=user_id]").val();
var imageId = $("input[name=image_id]").val();
var comment = $("textarea[name=comment]").val();
$.ajax({
method: 'POST',
url: urlComment,
data: {userId: userId, imageId: imageId, comment: comment, _token: token}
}).done(function(serverResponseData){
$("textarea[name=comment]").val("");
$('.comments').append('<p></p>');
})
});
答案 0 :(得分:2)
你可以通过返回json共振来访问ajax中的done方法中的数据返回
public function postComment(Request $request){
$userId = $request['userId'];
$imageId = $request['imageId'];
$commentText = $request['comment'];
$comment = new Comment();
$comment->user_id = $userId;
$comment->image_id = $imageId;
$comment->comment = $commentText;
$comment->save();
return response()->json(['comment'=>$comment]);
}
答案 1 :(得分:0)
您可以返回评论,它将在serverResponseData上 你只需要在方法的返回时添加它:
public function postComment(Request $request){
$userId = $request['userId'];
$imageId = $request['imageId'];
$commentText = $request['comment'];
$comment = new Comment();
$comment->user_id = $userId;
$comment->image_id = $imageId;
$comment->comment = $commentText;
$comment->save();
return $comment;
}
之后serverResponseData将保存该值,如果您希望它像访问数组那样访问它,您可以将ajax的返回类型设置为json: dataType:'json' < / p>