设置CouchDB支持JSONP跨域请求

19 July 2013

问题:
通过jQuery getJSON方法跨域访问CouchDB:

 var six_latest = poq.root + "poquotes/_design/poquotes/_view/by_year?&limit="
+ poq.max_quotes + "&descending=true&callback=?";
$.getJSON(six_latest, poq.handleMainQuotes);

Chrome console报错"Uncaught SyntaxError: Unexpected token :",Firebug报错"invalid label"

原因:
CouchDB默认按照Json格式返回,而jQuery在'callback=?'的JSONP请求模式下将结果按照script解析,因此无法解析返回结果

解决方法:
在CouchDB的配置文件中设置'allow_jsonp = true' (Windows中ini文件位于CouchDB\etc\couchdb\local.ini)

附:
allow_jsonp=false时返回Content-Type:text/plain,内容为:

{"total_rows":2,"offset":0,"rows":[
{"id":"99fd95b1bcfea3ca68013cba10003ccb","key":1915,"value":{"_id":"99fd95b1bcfea3ca68013cba10003ccb","_rev":"1-8c1b95f892379d6539d3a81a731fc9ec","type":"quote","author":"Robert Graves","text":"White flabbiness goes brown and lean,
Dumpling arms are now brass bars,
They’ve learnt to suffer and live clean,
And to think below the stars.","work":{"title":"A Renascence","link":"http://www.poetryfoundation.org/poem/240340","year":1915}}},
{"id":"99fd95b1bcfea3ca68013cba10001475","key":1915,"value":{"_id":"99fd95b1bcfea3ca68013cba10001475","_rev":"1-7fe040eb6d322a35a86d2f871b100ff0","type":"quote","author":"Thomas Hardy","text":"And as the smart ship grew
In stature, grace, and hue
In shadowy silent distance grew the Iceberg too.","work":{"title":"The Convergence Of The Twain","link":"http://www.poetryfoundation.org/poem/176678","year":1915}}}
]}

allow_jsonp=true时返回Content-Type:text/javascript,内容为:

/* CouchDB */jQuery19100955071453936398_1374199468922({"total_rows":2,"offset":0,"rows":[
{"id":"99fd95b1bcfea3ca68013cba10003ccb","key":1915,"value":{"_id":"99fd95b1bcfea3ca68013cba10003ccb","_rev":"1-8c1b95f892379d6539d3a81a731fc9ec","type":"quote","author":"Robert Graves","text":"White flabbiness goes brown and lean,
Dumpling arms are now brass bars,
They’ve learnt to suffer and live clean,
And to think below the stars.","work":{"title":"A Renascence","link":"http://www.poetryfoundation.org/poem/240340","year":1915}}},
{"id":"99fd95b1bcfea3ca68013cba10001475","key":1915,"value":{"_id":"99fd95b1bcfea3ca68013cba10001475","_rev":"1-7fe040eb6d322a35a86d2f871b100ff0","type":"quote","author":"Thomas Hardy","text":"And as the smart ship grew
In stature, grace, and hue
In shadowy silent distance grew the Iceberg too.","work":{"title":"The Convergence Of The Twain","link":"http://www.poetryfoundation.org/poem/176678","year":1915}}}
]});

下一篇: 理解iOS程序签名机制 →

blog comments powered by Disqus