0

I am learning JavaScript, and I need to read the data from a url (http://example.com?index=goog,dji), which will return the string below. Now I want to print the name and the value, in an html table

[ 
  { "id": "983582" ,"t" : ".DJI" ,"e" : "INDEXDJX" ,"l" : "15,081.47" ,"l_cur" : "15,081.47" ,"s": "0" ,"ltt":"4:35PM EDT" ,"lt" : "Aug 16, 4:35PM EDT" ,"c" : "-30.72" ,"cp" : "-0.20" ,"ccol" : "chr" },
  { "id": "694653" ,"t" : "GOOG" ,"e" : "NASDAQ" ,"l" : "856.91" ,"l_cur" : "856.91" ,"s": "0" ,"ltt":"4:00PM EDT" ,"lt" : "Aug 16, 4:00PM EDT" ,"c" : "-2.75" ,"cp" : "-0.32" ,"ccol" : "chr" }
]

output

INDEXDJX  - 15,081.47
GOOG - 856.91

How can I do so using JavaScript and HTML?

1
  • Please post what you have tried so far. You can learn about Ajax on MDN, how to parse JSON is answered here and how to process arrays/objects is answered here. Commented Aug 17, 2013 at 8:30

3 Answers 3

2

Try Jquery It is more easier than pure javascript since it requires only few lines of codes moreover jquery is also a javascript framework

you can implement it by adding jquery library in head as follows

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>

an following code under script tag

$.ajax({ 
    type: 'GET', 
    url: 'http://example.com?index=goog,dji', 
    dataType: 'json',
    success: function (data) { 
        $.each(data, function(index, element) {
            $('body').append($('<div>', {
                text: element.name
            }));
        });
    }
});

UPDATE

more precisely in your case this code will works fine

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function() {
                $.getJSON('http://example.com?index=goog,dji',function(data){
                    $('body').empty();
                    var html ='<table>';
                    $.each(data, function(entryIndex, entry){
                        $.each(entry, function(entrydataIndex, entrydata){
                            html += '<tr>';                   
                            html += '<strong>'+entrydataIndex+'</strong>'+'-'+ entrydata+'<br/>';               
                            html += '</tr">';                                       
                        });
                    });
                    html += "</table>";
                    $('body').append(html);                       
                });
                return false;

        });
</script>
</head>

<body>
</body>
</html>
Sign up to request clarification or add additional context in comments.

8 Comments

@Patsy Issa: JQuery is JS. You should have said: the OP did not ask for JQuery :) Anyway I doubt that the OP would have any advantage in implementing his own AJAX library aside from learning purposes.
Hi Sam, Thank you for reply.. but it is not working... just working is i due to return string have "//" at staring..
@monamona will you show me your output screen did your example.com?index retun json in proper format?
// [ { "id": "983582" ,"t" : ".DJI" ,"e" : "INDEXDJX" ,"l" : "15,081.47" ,"l_cur" : "15,081.47" ,"s": "0" ,"ltt":"4:35PM EDT" ,"lt" : "Aug 16, 4:35PM EDT" ,"c" : "-30.72" ,"cp" : "-0.20" ,"ccol" : "chr" } ,{ "id": "694653" ,"t" : "GOOG" ,"e" : "NASDAQ" ,"l" : "856.91" ,"l_cur" : "856.91" ,"s": "0" ,"ltt":"4:00PM EDT" ,"lt" : "Aug 16, 4:00PM EDT" ,"c" : "-2.75" ,"cp" : "-0.32" ,"ccol" : "chr" } ,{ "id": "22144" ,"t" : "AAPL" ,"e" : "NASDAQ" ,"l" : "502.33" ,"l_cur" : "502.33" ,"s": "0" ,"ltt":"4:00PM EDT" ,"lt" : "Aug 16, 4:00PM EDT" ,"c" : "+4.42" ,"cp" : "0.89" ,"ccol" : "chg" } ]
that is malformed json, it shouldn't have the // in the start of it. If you have control of the json output make sure it doesnt output the //
|
1

Pure javascript example, though using jQuery, as mentioned in Sam's answer, is easier

function loadJSON() {    
    var ajaxRequest;  
    try{
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    }catch (e){
        // Internet Explorer Browsers
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        }catch (e) {
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            }catch (e){
                // Something went wrong
                alert("Your browser broke!");
                return false;
            }
        }
    }

    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
                    //IF YOU ARE NOT ABLE TO REMOVE THE // FROM THE BEGINING OF 
                    //THE JSON DATA THEN YOU WILL NEED TO REMOVE IT BEFORE
                    //PARSING
                    var json = ajaxRequest.responseText".replace(/^\/\/\s/,"");

            //Parse json to an object
            var dataObj = JSON.parse(json);

            //Now you can access the array of objects
            console.log( dataObj[0].INDEXDJX );
            console.log( dataObj[1].GOOG );
        }
    }


    ajaxRequest.open("GET", "http://example.com?index=goog,dji", true);
    ajaxRequest.send(null); 
}

3 Comments

realy nice work.. as it is the proper answer to question... if it works
need more info than "this is not working", whats not working? are you getting error messages, if so what are they etc etc etc
Edited my answer to show it stripping the // from the json string before parsing if you are not able to change the server from putting it there.
0

you can do that using ajax, i will use jquery for shorter code p.s: "you are using Google stock please note that it is 15 mins late from the real market"

<html>
<head>
<title></title>
<meta charset="utf-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$("document").ready(function(){
 $.ajax({url:'http://example.com?index=goog,dji',dataType: 'json',success:function(data){
      var result="";
      $.each(data,function(index,stock){
          result+= stock.e+" - "+stock.l_cur+"<br/>";
      });
      $("body").append("<div>"+result+"</div>");
}});
});
</script>
</head>
<body>
Results:<br/>
</body>
</html>

1 Comment

Shouldn't use jQuery 2.x yet unless you know users won't be using IE 6,7,8 as 2.x no longer supports those browsers and there are quite a few people who still use those previous versions of ie.