javascript 如何解决 json 错误:SyntaxError: missing ; 在声明之前 {"products":[{"title":"xyz","id":1718,"created_at?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23014342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to solve json error : SyntaxError: missing ; before statement {"products":[{"title":"xyz","id":1718,"created_at?
提问by Sanjay Rathod
i have some code in ajax call like below
我在 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 );
}
});
when i run this code into firefox with fire bug. firebug shows response in perect json format but shows following error in firebug
当我将此代码运行到带有 fire bug 的 firefox 时。firebug 以 perect json 格式显示响应,但在 firebug 中显示以下错误
SyntaxError: missing ; before statement
{"products":[{"title":"xyz","id":1718,"created_at
so how can i solve it??
那我该如何解决呢??
回答by Quentin
You are telling jQuery to process the response as JSONP:
您告诉 jQuery 将响应处理为 JSONP:
dataType: 'jsonp'
… but the response is JSON, not JSONP.
… 但响应是 JSON,而不是 JSONP。
Get rid of the p
or get rid of the dataType
line entirely and let jQuery determine the data type from the Content-Type
of the response (which should be application/json
).
摆脱p
或dataType
完全摆脱该行,让 jQuery 从Content-Type
响应的确定数据类型(应该是application/json
)。
回答by Jay Blanchard
Change
改变
dataType: 'jsonp',
to
到
dataType: 'json',
Because you are getting JSON, not JSONP, back.
因为你得到的是 JSON,而不是 JSONP。
回答by Arman Ortega
In your controller make sure that you render the format correctly. example:
在您的控制器中,确保正确呈现格式。例子:
def view_product
data = Product.find params[:id]
render :json => data, :callback => params[:callback]
end
In your render method, there must have the :callbackparameter otherwise it will render in json instead of jsonp.
在您的渲染方法中,必须有:callback参数,否则它将在 json 而不是 jsonp 中渲染。