开发者

Giving a parser as attribute in getJSON jquery function

开发者 https://www.devze.com 2023-03-25 17:54 出处:网络
Function cue.getCueAsSource(); gives me a nice and clean JSON file that looks like this: { \"A\" : { \"B\" : [{\"value\" : \"brunos homepage\" , \"type\" : \"literal\"}]

Function cue.getCueAsSource(); gives me a nice and clean JSON file that looks like this:

{
"A" :
    {
        "B" : [{"value" : "brunos homepage" , "type" : "literal"}]
    }
}

I need to place that output in first argument of getJSON function 开发者_C百科so I can get whatever data I need from that JSON file. Since it will not accept function as a parameter, I'm placing it in a variable for it is a string (I have a hunch that there is something wrong with that).

var cueText = cue.getCueAsSource();

$.getJSON(cueText, function(json) {
    $('#meta').html('<p>Title: ' + json.A.B[0].value + '</p>');
});

But it throws me this error in firebug:

GET { "A" : { "B" : [{"value" : "brunos homepage" , "type" : "literal"}] } }
500 Internal Server Error

What is wrong? Is there any other way to place json output from some function into getJSON function? Thanks a lot. Again.


You don't want $.getJSON() for this. $.getJSON() is an alias to $.ajax() and is used to retrieve JSON formatted data from the server and pre-parse it into an object before giving it to you.

You already have a string of JSON, apparently, and simply need to parse it. Use:

var cueText = cue.getCueAsSource();
var cueObject = JSON.parse( cueText );
$('#meta').html('<p>Title: ' + cueObject.A.B[0].value + '</p>');

All browsers, except for IE, have the standard JSON API built in. For IE, downalod Crockford's json2.js and include it on your page. It is smart enough to leave the standard API alone if present, and provide it if not. I prefer to include it just ahead of jQuery so that jQuery is always using the standard API as well.

0

精彩评论

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