ruby on railsでajaxを使用するのが初めてです。私が望むもの:ユーザがクラス.link
(外部サイト、例えばwww.google.de)のリンクをクリックすると、データは - $(this).attr('id')
- を投稿/表示のrailsコントローラ#actionに送信する必要があります。 (!)これは正常に動作している、それにもかかわらず、私は構文エラーを得た:私はdataType: "json"
構文エラーが消滅を削除するとRails:構文エラー: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
これは私の資産/ JavaScriptの/ 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