【发布时间】:2017-05-18 20:45:55
【问题描述】:
我不熟悉在 ruby on rails 中使用 ajax。我想要什么:如果用户单击类.link 的链接(到外部站点,例如www.google.de),它应该将数据 - 即$(this).attr('id') - 发送到我的rails controller#action in posts /看法。这工作正常(!),但我得到一个语法错误:
parsererror SyntaxError:JSON.parse:JSON 数据的第 2 行第 1 列出现意外字符
堆栈跟踪: jQuery.parseJSON@http://localhost:3000/assets/jquery.self-660adc51e0224b731d29f575a6f1ec167ba08ad06ed5deca4f1e8654c135bf4c.js?body=1:9008:10
ajaxConvert@http://localhost:3000/assets/jquery.self-660adc51e0224b731d29f575a6f1ec167ba08ad06ed5deca4f1e8654c135bf4c.js?body=1:9332:19
完成@http://localhost:3000/assets/jquery.self-660adc51e0224b731d29f575a6f1ec167ba08ad06ed5deca4f1e8654c135bf4c.js?body=1:9786:15
.send/callback@http://localhost:3000/assets/jquery.self-660adc51e0224b731d29f575a6f1ec167ba08ad06ed5deca4f1e8654c135bf4c.js?body=1:10303:8
fakeviews.self-2c717c6e0cc666118cfc1f98874e4c23dad3ccc9e219b4a857306ed44e947a7b.js:16:25
这是我的资产/javascripts/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");
}
});
});
当我删除 dataType: "json" 时,语法错误消失了。那么到底发生了什么(因为我的代码按我想要的方式工作,我仍然想知道为什么会出现语法错误)?
这是我的控制器/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指的是服务器应该发回给你的数据类型。
标签: javascript jquery ruby-on-rails json ajax