简体   繁体   中英

Display data from json array using ajax

I have the following code on index page the script contains part of the code that will call the data from test page

<div class="leftbox" id="proddisplay">

</div>

var onSubmit = function(e) {
  var txtbox = $('#txt').val();
  var hiddenTxt = $('#hidden').val();
  $.ajax({
    type: 'post',
    url: 'test.php',
    data: {
      txt: txtbox,
      hidden: hiddenTxt
    },
    cache: false,
    success: function(returndata) {
      $('#proddisplay').html(returndata);
      console.log(returndata);
    },
    error: function() {
      console.error('Failed to process ajax !');
    }
  });
};

From test.php i am getting json array that looks like this

[1,2,"text","text2"]

I want to display the json array data in a tabular form and display it inside the div. the view of table should be something like this (it will have some css of its own)

static text: 1
static text: 2
static text: text
static text: text2

static text will be given by me and remains the same throughout however the values of array would change. can anyone tell how i can do so

individually i can display the data from json, but here i also need to put json data in a table and then put that table within a div

First of all you need to encode the array in php before sending to frontend, use json_encode() and then decode it in the success function using JSON.parse() . After just run a loop throught the array.

var onSubmit = function(e) {
 var txtbox = $('#txt').val();
 var hiddenTxt = $('#hidden').val();
 $.ajax({
   type: 'post',
   url: 'test.php',
   data: {
     txt: txtbox,
     hidden: hiddenTxt
   },
   cache: false,
   success: function(returndata) {
     var returneddata = JSON.parse(returndata);
     var htmlData= '';
     for(var i=0; i<returneddata.length; i++){
        htmlData+= 'static text: '+returneddata[i]+' <br>';
     }
     $('#proddisplay').html(htmlData);
     console.log(returndata);
   },
   error: function() {
     console.error('Failed to process ajax !');
   }
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM