开发者

CouchDB getJSON not returnng what I expected

I have a test account on iriscouch

I am trying to write a routine to process the JSON returned.

function getMyJson(url) {
    $('#dispJson').html('<h3>Json Data from: ' + url);
    data = $.getJSON(url);
    $.each(data, function(key, val) {
        $('#dispJson').append('key: ' + key + ' Val: ' +  val + '<br />');
    });
    return true;
};

But I appear to be getting JSON back, but not what I was expecting

Results

key: readyState Val: 1
key: setRequestHeader Val: function ( name, value ) { if ( !state ) { var lname = name.toLowerCase(); name = requestHeadersNames[ lname ] = re开发者_StackOverflow中文版questHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }
key: getAllResponseHeaders Val: function () { return state === 2 ? 
......
jQuery.type( elem ); if ( type === "array" ) { deferred.done.apply( deferred, elem ); } else if ( type === "function" ) { callbacks.push( elem ); } } if ( _fired ) { deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] ); } } return this; }
key: statusCode Val: function ( map ) { if ( map ) { var tmp; if ( state < 2 ) { for( tmp in map ) { statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; } } else { tmp = map[ jqXHR.status ]; jqXHR.then( tmp, tmp ); } } return this; }

In fact I get that response from whatever url I use on the IrisCouch site.

I have JSONP set to true and I also tested with ?callback=? appended to the URL.

I am hoping someone recognises the output I am getting and can advise me as to what I have misunderstood or done wrong.

Thanks mcl


You're setting data to the XHR object returned by jQuery. Remember that XHR is asynchronous so you can't expect the result to be immediately available.

Instead, you should be doing something like this:

$.ajax({
    url: url,
    dataType: 'json',
    success: function(data) {
        $.each(data, function(key, val) {
            $('#dispJson').append('key: ' + key + ' Val: ' +  val + '<br />');
        });
    }
});

Be sure to read through the documentation: http://api.jquery.com/jQuery.getJSON/


Many thanks. It is now working as I expected. The dataType does need to be specified as 'jsonp' (I think because it is a cross domain access) and I added type 'get' for my clarity.

$.ajax({
    url: myurl,    // eg http://mysite.iriscouch.com/mydatabase or whatever valid curl command
    type: 'get',
    dataType: 'jsonp',
    success: function(data) {
        $.each(data, function(key, val) {
            $('#dispJson').append('key: ' + key + ' Val: ' +  val + '<br />');
        });
    }
});

Just need to figure out how to identify Values as arrays and then process them. I imagine I could end up with many levels and somewhere there is a beautiful hierarchical tree routine that does it all. But hey, we have to learn it from scratch.

Thanks again

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜