0

Continuing to develop my first web-service, faced a new problem... I have a javascript function, which is provide a JSON object as array.

function RequestData(i){
    var xhr = new XMLHttpRequest();
    xhr.open('GET', '/getitemID='+i, true);
    xhr.send();
    xhr.onreadystatechange = function() { // (3)
        if (xhr.readyState != 4) return;
        if (xhr.status != 200) {
            alert(xhr.status + ': ' + xhr.statusText);
        } else {
            alert(xhr.responseText);
            var jsonData = JSON.parse(xhr.responseText);
            for (var j=0; j< jsonData.length; j++  ){
                alert(jsonData[j].name);
            }
        }

    }
    xhr.close();
}

there is an array with entities in jsonData like "name", "description", etc

The question is, how can i display a resulting JSON array on the html body of the page? like in foror foreach cycle

need just a simple example. imagine this how the JS file make the content of page

var contentString = '<div id="content">'+
    '<div id="bodyContent">'+
    '<button onclick="RequestData('+i+')">Load Data!</button>'+
    '</div>'+
    '</div>';

i want to insert a result from RequestData() function into the content of variable "var contentString"

4
  • you want to save the response in contentstring, correct > ? Commented May 22, 2015 at 10:22
  • yes i want to show the result from var jsonData in the table, in the html body. single row for each entity in jsonData. Commented May 22, 2015 at 10:24
  • Can you show the json response format? Commented May 22, 2015 at 10:38
  • @user1935987, just so you know the answer you've selected is very inefficient in terms of DOM manipulation. Commented May 22, 2015 at 10:56

2 Answers 2

0

You should probably use a callback here.

function RequestData(i, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', '/getitemID='+i, true);
    xhr.send();
    xhr.onreadystatechange = function() { // (3)
        if (xhr.readyState != 4) return;
        if (xhr.status != 200) {
            alert(xhr.status + ': ' + xhr.statusText);
        } else {

            // pass the parsed data as the parameter of the callback
            callback(JSON.parse(xhr.responseText));
        }

    }
    xhr.close();
}

// i is the id we're passing into the function
// and that is used in the xhr.open command
// this is an example
var i = 23;

// i gets passed in as the first parameter,
// the json gets passed as the second parameter to the callback
RequestData(i, function (json) {

  // we create a little template using an array
  var tmpl = [
    '<div id="content"><div id="bodyContent">',
    '<button onclick="RequestData(#name)">Load Data!</button></div></div>'
  ].join('');

  var body = document.querySelector('body');

  for (var i = 0, l = json.length; i < l; i++) {

     // replace the name in the template with the json name for that index
     var html = tmpl.replace('#name', json[i].name);

     // use insertAdjacentHTML to add that HTML string to the body element
     body.insertAdjacentHTML('afterbegin', html);
  }

});

You can read more on the widely supported insertAdjacentHTML on the MDN page (it's the first I've heard of it!). And here's an example of it working.

Sign up to request clarification or add additional context in comments.

7 Comments

but, why is it better to use a callback? and, from where did i pass a callback to "function RequestData(id, callback)" here?
It makes your code simpler. And the function is the one that's passed as the second argument in the line: RequestData(id, function (json) {
why can't i transfer id in callback function? RequestData(id, function (json) { "unresolved type of variable id"
else if i do this: callback(i, JSON.parse(xhr.responseText)); RequestData(function (i, json) {} getting a "Uncaught TypeError: callback is not a function" error. i'm really new to web-programming, can't get, what is wring here? how to pass 'i' ?
i is the first parameter that represents the query id you're using. I used id in my example because it's more explanatory. There's no need to pass it back in the callback. So just use my code for that. Then you do RequestData(i, function (json because you're passing in that id into RequestData as the first parameter. I've updated my code to make this more explanatory.
|
0
for (var j=0; j< jsonData.length; j++  ){
    GetHTML(j);
}

function GetHTML(j) {
    var divwrapper =  document.CreateElement('div');
    var innerdivwrapper =  document.CreateElement('div');
    var textnode = document.createTextNode("my Name :" + j.Name + 'desc' + j.Description); 
    innerdivwrapper.appendChild(textnode);
    divwrapper.appendChild(innerdivwrapper);
    document.getElementsByTagName('body').appendChild(divwrapper);
}

9 Comments

The OP isn't using jQuery.
Your code won't run (missing ), capital F in Function, using j as iterating variable but indexing the array with i) and could have nicer formatting.
Formatting still terrible, and document.getElementByTagName('body') won't work, should be document.getElementsByTagName('body')[0]
sorry abt that, will correct, but still it gives an idea to solve the problem.
Yeah, it's just nice with working and decently looking code :) -1 removed now, despite the formatting.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.