如何解决json错误:SyntaxError:缺失;在语句 {"products":[{"title":"xyz","id":1718,"created_at?

问题描述 投票:0回答:4

我在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 );
                }
            });

当我用 fire bug 将这段代码运行到 Firefox 中时。 firebug 以正确的 json 格式显示响应,但在 firebug 中显示以下错误

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

那么我该如何解决呢??

javascript jquery ajax json callback
4个回答
3
投票

您正在告诉 jQuery 将响应作为 JSONP 进行处理:

dataType: 'jsonp'

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

去掉

p
或完全去掉
dataType
行,让 jQuery 根据响应的
Content-Type
确定数据类型(应该是
application/json
)。


1
投票

改变

dataType: 'jsonp',

dataType: 'json',

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


1
投票

在控制器中确保正确渲染格式。 示例:

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

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


0
投票

有多困难?看起来像

© www.soinside.com 2019 - 2024. All rights reserved.