Jose
Jose

Reputation: 617

Using xhrGET to get object arrays from a server

I currently have an object array that I wish to call into my HTML page using xhrget. Here's a snippet of said object array from my server:

[ 
    { "Name":"John" , "id":"1" }, 
    { "Name":"Anna" , "id":"2" }, 
    { "Name":"Peter" , "id": "3" }
    { "Name":"Peter" , "id": "4" }
]

I therefore then call this object array using xhrget

require(["dojo/request", "dojo/dom", "dojo/dom-construct", "dojo/json", "dojo/on", "dojo/domReady!", "dojo/_base/xhr"], 

function (dom,json,request,domconst,on,xhr){

    dojo.ready(function(){

        var targetNode = dojo.byId("licenseContainer");  

        var xhrArgs = {
            url: "http://141.41.11.71:3000/page.json",
            handleAs: 'json',
            timeout : 2000,

            load: function(data){


            targetNode.innerHTML = data;
        },
        error: function(error){
            targetNode.innerHTML = "An unexpected error occurred: " + error;
        }
    }

    var deferred = dojo.xhrGet(xhrArgs);
    });
});

I essentially wish to put a specified object into the node/div that I have specified by the ID. However I keep getting the error : TypeError: 'undefined' is not a function.

Any advice?

Upvotes: 1

Views: 336

Answers (1)

Musa
Musa

Reputation: 97727

You can access the mane property with value john as data[0].Name

    var xhrArgs = {
        url: "http://141.41.11.71:3000/page.json",
        handleAs: 'json',
        timeout : 2000,

        load: function(data){


        targetNode.innerHTML = data[0].Name;
    },
    error: function(error){
        targetNode.innerHTML = "An unexpected error occurred: " + error;
    }
}

Edit

To show all the names you'll have to loop through the array.

        load: function(data){
            var html = '';
            for (var i = 0; i < data.length; i++)
                html += data[i].Name+'<br>';
            targetNode.innerHTML = html;
    },

Upvotes: 1

Related Questions