【问题标题】:Rails: Syntax error: JSON.parse: unexpected character at line 2 column 1 of the JSON dataRails:语法错误:JSON.parse:JSON 数据的第 2 行第 1 列出现意外字符
【发布时间】: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


【解决方案1】:

您需要使用JSON.stringify 首先将您的对象序列化为 JSON,然后指定内容类型以便您的服务器理解它是 JSON。

$.ajax({
             url: "/posts/view", 
            type: "POST",
        dataType: "json",
        headers: {
          'Content-Type': "application/json"
        }, 
        data: JSON.stringify({ post_id: id }), 

解析时出现语法错误,因为 Rails 无法识别传递的数据(因为它不是有效的 JSON 字符串)。

  • contentType 指定发送到服务器的数据格式为 部分请求
  • dataType 指定客户端要接收的数据的预期格式(浏览器)。

还将方法从GET 更改为POSTGET 请求(至少通常)没有消息正文。如果你设置为GET,它将被转换为URL字符串的参数。

【讨论】:

  • 感谢您的快速回复:)。我已按照您的建议更改了代码,语法错误消失了。但是现在我的 rails posts#view 控制器操作似乎不再找到正确的Post。我是否也必须更改其中的某些内容(我的问题中包括了我的 rails controller#action)?现在在 Javascript 控制台中,我收到错误 error Not found
  • 您是否检查了 rails 日志,哪个有效负载传递给了操作? 另外 StackOverflow 不是你的调试工具,试着理解问题
  • 在我的 Rails 日志中,我收到此错误:'Completed 404 Not Found in 3ms (ActiveRecord: 0.4ms) ActiveRecord::RecordNotFound (Couldn't find Fpost with 'id'=):'跨度>
  • 我说的是传递给动作的参数。
  • 哎呀,对不起。这些是传递给操作的参数:由 PostsController#view 作为 JSON 处理参数:{"{\"post_id\":\"635\"}"=>nil, "_"=>"1483539580899", “发布”=>{}}
【解决方案2】:

您的 data 应该是有效的 JSON 字符串。您可以验证它是否有效by pasting it here。要在您的情况下获得有效的 JSON 字符串,请使用 JSON.stringify(JavaScriptObject):

$(document).on("click", '.link', function() {

var id = $(this).attr('id');
var dataObject = {};
dataObject.post_id = id;
$.ajax({
    url: "/posts/view", 
    cache: false,
    type: "GET",
    dataType: "json",
    data: JSON.stringify(dataObject)
    complete: function() {},
    success: function(data, textStatus, xhr) {
        alert("success");
    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.log(textStatus, errorThrown);
        alert("error");
    }
});
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 2020-01-11
    • 2020-10-13
    • 2016-01-30
    • 2019-05-11
    • 2021-10-12
    • 1970-01-01
    相关资源
    最近更新 更多