getjson jquery parsing an array

前端 未结 3 1741
甜味超标
甜味超标 2021-01-06 06:40

Got the simplified array working see below

Following up on the complicated array to parse see here.


TLDR: Want to get each heading fro

相关标签:
3条回答
  • 2021-01-06 06:48

    Hopefully this example will point you in the right direction


    <html>
    <head>
      <title>Stackoverflow</title>
      // ** POINT THIS TO A VALID jquery.js LOCATION
      <script src="jquery.js" type="text/javascript"></script>
      <script>
        var days = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ];
        // *****************************************************
        // This is your data from getJSON if correctly formatted
        var data = '{"Days":[ {"Sunday":"10.00"}, {"Monday":"12.00"}, {"Tuesday":"09.00"}, {"Wednesday":"10.00"}, {"Thursday":"02.00"}, {"Friday":"05.00"}, {"Saturday":"08.00"}]}';
        runUpdate = function() {
          // *******************************************************
          // Clear the div of all data by replacing it
          $('#testfield').replaceWith('<div id="testfield"></div>');
          var dataObject= $.parseJSON( data );
          $.each( dataObject.Days, function (index, value) {
            // ********************************************
            // Append new elements to the newly created div
            $('#testfield').append("<p>"+days[index]+": "+value[ days[index] ]+"</p>");
          });
        };
    
        runReset = function() {
          $('#testfield').replaceWith('<div id="testfield">This is original text.</div>');
        };
      </script>
    </head>
    <body>
      <div id="testfield">
        This is original text.
      </div>
      <div>
        <input type="button" value="Run Update" onclick="runUpdate();" />
        <input type="button" value="Reset" onclick="runReset();" />
      </div>
    </body>
    </html>
    
    0 讨论(0)
  • 2021-01-06 06:57

    There is an error in your JSON data: you're not using colons after "d" in the last three items. Is this an example of real data that your application is using, or example data to demonstrate your problem?

    0 讨论(0)
  • 2021-01-06 07:05
    $.getJSON(url,
        function(data){
          $.each(data.items, function(i,item){
          $('#testfield').html('<p>' + item.d.title + '</p>');
          });
        });
    

    In this code you're going to end up replacing the HTML of the item with ID of 'testfield' with the value over and over ... you might want to try using jQuery.append to add all entries as you've specified above

    $.getJSON(url,
        function(data){
          $.each(data.items, function(i,item){
          $('#testfield').append('<p>' + item.d.title + '</p>');
          });
        });
    
    0 讨论(0)
提交回复
热议问题