编程语言
首页 > 编程语言> > javascript-JSON ParseError即使请求成功

javascript-JSON ParseError即使请求成功

作者:互联网

即使从服务器返回成功,我仍收到JSON parseerror.这是我的保存代码,其中总是运行fail()

@model.save()
  .fail(=> @resetForm() )
  .always (obj, error) ->
    console.log obj
    console.log obj.responseText
    console.log JSON.parse(obj.responseText)

这是我的错误对象:

"parsererror"
"No conversion from text to http://api2.local/users/auth"

一些注意事项:

我正在使用Jquery 1.8.3和Backbone 0.9.9
服务器使用json正确响应-这是我的响应标头

Access-Control-Allow-Headers:origin, x-requested-with, content-type, accept
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin:*
Access-Control-Max-Age:86400
Connection:Keep-Alive 
Content-Length:202
Content-Type:application/json; charset=utf-8
Date:Fri, 21 Dec 2012 18:46:25 GMT
Keep-Alive:timeout=5, max=100
Server: xxx
X-Powered-By:PHP/5.3.1

console.log JSON.parse(obj.responseText)正确地给了我一个JSON对象

编辑:请求标头

Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Content-Length:54
Content-Type:application/json
Host:api2.local
Origin:http://localhost:3000
Pragma:no-cache
Referer:http://localhost:3000/login
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.101 Safari/537.11
X-Requested-With:XMLHttpRequest

编辑:通过POST请求有效载荷

{"email":"x@x.com","password":"xxx"}

编辑:响应有效负载

{
"user_id":"xx",
"first_name":"xxx",
"last_name":"xxx",
"email":"x@x.com",
"role":"xxxx",
"date_joined":"xxx"
}

解决方法:

Ahhhh-编程有时会很烦人.终于弄清楚了-谢谢大家的帮助,但这是一个简单的coffeescript编译问题

所以在我之前

$.ajaxPrefilter ( (options, originalOptions, jqXHR) -> 
 options.url = "#{ API_URL }" + options.url
)

编译后将返回options.url和$.ajaxPrefilter.无论出于何种原因,Jquery都会在ajaxPrefilter函数中将options.url设置为DataTypes argument.解决方案是返回false:

$.ajaxPrefilter \
  (options, originalOptions, jqXHR) -> 
    options.url = "#{ API_URL }" + options.url
    no 

给出正确的编译版本

return $.ajaxPrefilter(function(options, originalOptions, jqXHR) {
  options.url = ("" + API_URL) + options.url;
  return false;
});

标签:coffeescript,backbone-js,http-headers,javascript,jquery
来源: https://codeday.me/bug/20191031/1976080.html