How to populate template with AJAX data, need some help


#1

I got te top late to be loaded with router, and can load data with AJAX request
but I can’t push them back inside the template
and i don’t know I to pass a variable to the template I’m going to load

I need to specify the ID to my endpoint to load the data i need

this is what I got to work so far

<!-- component template -->
<template>
  <div class="page">
<div class="navbar">
  <div class="navbar-inner">
    <div class="title">{{title}}</div>
  </div>
</div>
<div class="page-content">
  <div class="list simple-list">
    <ul>
      {{#each names}}
        <li>{{this}}</li>
      {{/each}}
    </ul>
  </div>
  <div class="block block-strong">
     <a href="#" class="link back">
	        <i class="icon icon-back"></i>
			<span class="ios-only">Back</span>
    </a>
  </div>
</div>
  </div>
</template>

<script>
  
  /* https://framework7.io/docs/request.html */
  
  // script must return component object
  return {
data: function () {
  return {
    title: 'Component Page',
    names: [],
  }
},
	on: {
  
  pageInit() {
	      
    var self = this;
    var app = self.$app;
    
		app.request.get('../json/test-d-01.json?id=xxx', function (data) {
	       
	       var d = JSON.parse(data);
	       
	       console.log(d); 
		   console.log(d.ptitle);
		   
		   return {
	        title: d.ptitle,
	        names: d.pnames,
	      }
		   
		   /*self.$setState({
	            names: jsondata.names,
	          });*/
		   
		});
		
  },
  
}
  }
</script>

#2

I see you commented self.$setState, why? This is the way to put it in data and update template


#3

you need to refresh the page with this when the AJAX finish to reload the template:

app.views.current.router.refreshPage()

its will refresh the page and renew the scroll to top 0, to fix this you need to save the current position of page-content DIV:

$(’#pageContent’).scroll(function() {
if (app.boolChange == undefined) {
app.scrollTop = $(’#pageContent’).prop(‘scrollTop’)
}
})

if (app.boolChange != undefined) {
delete app.boolChange
}

and when the page reload finish, set the position saved:

if (app.scrollTop != undefined) {
$(’#pageContent’).animate({ scrollTop: app.scrollTop }, 0, function () { })
}


#4

because not sure why but

app.request.get('../json/test-d-01.json?id=zzz', function (data) {
       
		var d = JSON.parse(data);
		
		console.log(d); 
		console.log(d.pnames);
		
		/*self.$setState({
			names: ["aa","bb","cc"],
		});*/
		
		self.$setState({
			names: d.names,
		});
	   
	});

if I hardcode the array ( first comment ) seems to work
if I pass JSON it doesn’t work

console log output this

(3) [“John”, “Vladimir”, “Timo”]
0: “John”
1: “Vladimir”
2: “Timo”
length: 3

so it seems to be right

TST JSON is like this

{“ptitle”:“D Page”,“pnames”:[“John”,“Vladimir”,“Timo”]}

to use jQuery, that i more comfortable with, to build the page is a bad idea?