问题
I'm using the following jQuery code to get a JSON file from CouchDB.
Function getURL() {
var api_url = 'http://127.0.0.1:5984/couchcontentqueue/_design/DocCollections/_view/view_all_by_url_name?key="favorite-flickr-photos"&?callback=?';
$.getJSON(api_url, function(json) {
var type = json.type;
var desc = json.description;
$("#dropBox h3").html(type);
$("#dropBox p").html(desc);
});
};
When I do a GET on that URL it provides back the following:
{"total_rows":6,"offset":5,"rows":[ {"id":"f5ba37e5af406ab079d596f7a1f30a2d","key":.... ]}
Firebug gives me the following error: invalid label http://127.0.0.1:5984/couchcontentqueue/_design/DocCollections/_view/view_all_by_url_name?key=%22favorite-flickr-photos%22&?callback=jsonp1304111285023 Line 1
I can't figure out how to get past that first line to get to the actual JSON object. Any ideas? Thanks.
回答1:
?callback=
It looks like you are trying to do a JSONP request, but:
{"total_rows":6, ...
Is a plain JSON response and not a JSONP call. If you don't mean to do a cross-domain JSONP request, get rid of the callback
parameter and have jQuery parse the response as normal JSON.
If you do need to do cross-domain JSONP requests, and you understand the security risks of that, make sure you're using an up-to-date CouchDB version and add the directive:
allow_jsonp = true
to the .ini file in the [http]
section.
invalid label
is what you get when you try to execute/eval
a string containing a JSON object. It is a quirk of JS parsing that the "x"
in {"x": "foo"}
is taken as a JavaScript ‘label’ (used rarely for continue
statements) in a statement block, rather than an object property name in an object literal expression.
jQuery will use script execution instead of JSON parsing when it thinks you are doing a JSONP request. Having the ‘callback=’ parameter in your URL magically makes it think that.
回答2:
var key = json.rows[0].key;
var doctype = json.rows[0].value.doc_type;
so on and so forth...
来源:https://stackoverflow.com/questions/5837476/how-to-get-past-the-total-rows-when-parsing-json-from-couchdb