레일에 루비에서 ajax를 처음 사용했습니다. 내가 원하는 것 : 사용자가 클래스 .link
(외부 사이트, 예 : www.google.de)의 링크를 클릭하면 게시물 /보기의 rails 컨트롤러 # action에 데이터, 즉 $(this).attr('id')
을 전송해야합니다. 이것은 잘 작동되고, 그럼에도 불구하고 나는 구문 오류가있어 (!) :레일 : 구문 오류 : JSON.parse : JSON 데이터의 2 행 1 열에서 예기치 않은 문자
parsererror SyntaxError: JSON.parse: unexpected character at line 2 column 1 of the JSON data
Stack-Trace: [email protected]http://localhost:3000/assets/jquery.self-660adc51e0224b731d29f575a6f1ec167ba08ad06ed5deca4f1e8654c135bf4c.js?body=1:9008:10
[email protected]http://localhost:3000/assets/jquery.self-660adc51e0224b731d29f575a6f1ec167ba08ad06ed5deca4f1e8654c135bf4c.js?body=1:9332:19
[email protected]http://localhost:3000/assets/jquery.self-660adc51e0224b731d29f575a6f1ec167ba08ad06ed5deca4f1e8654c135bf4c.js?body=1:9786:15
.send/[email protected]http://localhost:3000/assets/jquery.self-660adc51e0224b731d29f575a6f1ec167ba08ad06ed5deca4f1e8654c135bf4c.js?body=1:10303:8
fakeviews.self-2c717c6e0cc666118cfc1f98874e4c23dad3ccc9e219b4a857306ed44e947a7b.js:16:25
이 내가 dataType: "json"
을 삭제하면 내 자산이 /가/views.js.erb
$(document).on("click", '.link', function() {
var id = $(this).attr('id');
$.ajax({
url: "/posts/view",
cache: false,
type: "GET",
dataType: "json",
data: { post_id: id }, // Here seems to be the problem?
complete: function() {},
success: function(data, textStatus, xhr) {
alert("success");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
alert("error");
}
});
});
구문 오류가 사라 자바 스크립트입니다 . 그래서 정확히 무슨 일이 벌어지고 있는가? (필자의 코드는 내가 원하는 것처럼 작동하고 있기 때문에 왜 구문 오류가 있는지 궁금해한다)?
이것은 내 컨트롤러/posts_controller.rb보기 액션
def view
@post = Post.find(params[:post_id])
@post.views.create(user_id: current_user.id)
respond_to do |format|
format.html { redirect_to posts_path }
format.js {render json: @post }
end
end
보내는 응답이 유효한 JSON이 아닙니다. 요청에서 responseText를 포함하도록 질문을 편집 할 수 있습니까? –
'dataType'은 서버가 다시 보내야하는 데이터 유형을 나타냅니다. – elementzero23