aag
aag

Reputation: 728

extract elements from Ajax-JSON

I am conversant with PHP but I am a beginner with AJAX, and JSON is driving me crazy.

My PHP script delivers a simple JSON string, e.g.

    {"bindings": [ {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},
    {"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"}, 
    {"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"} ] } I 

retrieve it as follows:

var fillDataMasterTable = $.ajax({          
    url: "/php/PrepareGoogleDataTable.php" +"?"+
                "SensorString="+SensorString + "&"+
                "TableType=" + TableType +"&"+
                "NoAbscissaBins=" + NoAbscissaBins + "&"+
                "DataTableName=" + DataTableName +"&"+
                "TimeUnit=" + TimeUnit +"&"+
                "TimeStart=" + TimeStart,          
    dataType:'json',          
    async: false          
    }).responseText;    

 $('#debug_div').html(fillDataMasterTable);

That works fine, and I get my JSON string back. But how can I access the individual values? I tried:

          $('#debug_div').html(fillDataMasterTable.bindings);

but that just doesn't work. I am certainly doing something abysmally stupid here, and I am a bit ashamed - but I do need some hand-holding to get myself started..

Upvotes: 0

Views: 110

Answers (2)

Engineer
Engineer

Reputation: 48813

reponseText is a property of XMLHttpRequest object,and it will not be a JSON object after request.It'll be a String.And it does not metter,whether you specify "dataType" as "json".

So you need to convert it to json object:

 fillDataMasterTable = JSON.parse(fillDataMasterTable);

and then you can access properties like this:

 fillDataMasterTable.bindings

Upvotes: 4

Suave Nti
Suave Nti

Reputation: 3757

Use Jquery like this :

$.each(fillDataMasterTable.bindings, function(i, object) {
            $.each(object, bindings(property, value) {
                $('#debug_div').html(value);
            });
        });

Upvotes: 1

Related Questions