【问题标题】:how to solve json error : SyntaxError: missing ; before statement {"products":[{"title":"xyz","id":1718,"created_at?如何解决 json 错误:SyntaxError: missing ;在声明 {"products":[{"title":"xyz","id":1718,"created_at?
【发布时间】:2014-05-25 17:05:52
【问题描述】:

我在 ajax 调用中有一些代码,如下所示

$.ajax({
                url: query_string,
                cache: true,
                type: 'GET',
                async: false, // must be set to false
                success: function (data, success) {
                alert(jquery.parseJSON(data));
                  alert('success');
                  //alert(data);
                  //alert(success);
                },
                dataType: 'jsonp',
                error :function( jqxhr, textStatus, error ) { 
                    var err = textStatus + ', ' + error;
                    alert(err);
                },
                complete: function (jqxhr, textStatus ){
                //alert( "complete: " + JSON.stringify(jqxhr)+" "+ textStatus );
                }
            });

当我将此代码运行到带有火错误的 Firefox 中时。 firebug 以完美的 json 格式显示响应,但在 firebug 中显示以下错误

SyntaxError: missing ; before statement
{"products":[{"title":"xyz","id":1718,"created_at

那我该如何解决呢??

【问题讨论】:

  • 为您解析响应数据。摆脱 jquery.parseJSON 而只是 alert(data)
  • parsererror, Error: jQuery111005023312801262618_1397224574072 was not called 以上错误显示在错误功能警报中

标签: javascript jquery ajax json callback


【解决方案1】:

确保在您的控制器中正确呈现格式。 示例:

def view_product
    data = Product.find params[:id]
    render :json =>  data, :callback => params[:callback]
end

在您的渲染方法中,必须有 :callback 参数,否则它将以 json 而不是 jsonp 渲染。

【讨论】:

  • 是的,你是对的。您还必须在该操作上禁用 protect_from_forgery 才能使其正常工作。
【解决方案2】:

改变

dataType: 'jsonp',

到

dataType: 'json',

因为您返回的是 JSON,而不是 JSONP。

【讨论】:

  • 但是如果我使用 json 没有任何响应,因为它是跨域的
  • 您请求的 URL 是否允许您添加回调 =?到 URL 字符串?如果设置正确,将返回 JSONP。
  • 到 URL 字符串的末尾,所以你要添加 &callback=?许多 API 实现了返回 JSONP
  • 我添加了但结果相同
  • parsererror, Error: jQuery111005023312801262618_1397224574072 was not called 以上错误显示在错误功能警报中
【解决方案3】:

您告诉 jQuery 将响应作为 JSONP 处理:

dataType: 'jsonp'

…但响应是 JSON,而不是 JSONP。

去掉p或者完全去掉dataType这一行,让jQuery从响应的Content-Type(应该是application/json)中判断数据类型。

【讨论】:

  • 但如果我使用 json 则没有任何响应,因为它是跨域的
  • 如果你想使用 JSONP,那么你请求数据的服务器必须给你 JSONP。请参阅this question 了解替代方案。
  • parsererror, Error: jQuery111005023312801262618_1397224574072 was not called 以上错误显示在错误功能警报中
猜你喜欢
  • 2016-12-26
  • 1970-01-01
  • 2013-06-11
  • 2019-09-16
  • 2017-05-19
  • 2017-09-11
  • 2020-08-05
  • 2021-10-11
相关资源
最近更新 更多