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?

Bart
  • 19,692
  • 7
  • 68
  • 77
SmartDev
  • 481
  • 3
  • 11
  • 30
  • Please post what you have tried so far. You can [learn about Ajax on MDN](https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started), how to parse JSON is answered [here](http://stackoverflow.com/q/4935632/218196) and how to process arrays/objects is answered [here](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json). – Felix Kling Aug 17 '13 at 08:30

3 Answers3

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>
  • @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. – nico Aug 17 '13 at 08:27
  • Hi Sam, Thank you for reply.. but it is not working... just working is i due to return string have "//" at staring.. – SmartDev Aug 17 '13 at 08:41
  • @monamona will you show me your output screen did your http://example.com?index retun json in proper format? –  Aug 17 '13 at 08:48
  • // [ { "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" } ] – SmartDev Aug 17 '13 at 08:52
  • 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 // – Patrick Evans Aug 17 '13 at 08:56
  • yes may be // is outputted by your server program please have a look –  Aug 17 '13 at 08:58
  • Hi Sam/Patrick, Thank you for reply.. but i dont have control on server which is third party.. So basically i need to handle that.. and remove "//" – SmartDev Aug 17 '13 at 09:58
  • Hi @monamona in the above UPDATED code you need only remove "//" the code works fine for the json as i tested –  Aug 20 '13 at 06:04
2

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); 
}
Patrick Evans
  • 41,991
  • 6
  • 74
  • 87
  • realy nice work.. as it is the proper answer to question... if it works –  Aug 17 '13 at 08:45
  • need more info than "this is not working", whats not working? are you getting error messages, if so what are they etc etc etc – Patrick Evans Aug 17 '13 at 08:54
  • 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. – Patrick Evans Aug 17 '13 at 09:01
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>
Bakly
  • 640
  • 6
  • 18
  • 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. – Patrick Evans Aug 17 '13 at 08:45