Json Method for Front and Background Transport Using js

Keywords: JSON JQuery Fragment PHP

No matter what framework is used, there is a problem of transferring data from controller to Html page or jsp page. The most common way is to transfer Json string. In the past, there was some ambiguity about this knowledge. Now I'll sort it out.


[Jquery Basic Method]


Jquery and internal encapsulated ajax are commonly used to implement value transfer. Let's first look at jquery's get () and post () grammars. The get () method is to get data from the server. Its main parameters are to get the background request address and the callback function responsible for processing:


    $.get(URL,callback);


$("button").click(function(){
  $.get("demo_test.php",function(data,status){
    alert("data: " + data + "\n state: " + status);
  });
});

Post requests data through HTTP post method:

    $.post(URL,data,callback);


$("button").click(function(){
    $.post("/try/ajax/demo_test_post.php",
    {
        name:"Rookie tutorial",
        url:"http://www.runoob.com"
    },
        function(data,status){
        alert("data: \n" + data + "\n state: " + status);
    });
});


[spring mvc framework + Jquery ajax]

controller of spring mvc framework returns Map < String, Object > type parameter to js through annotation method.

@RequestMapping("update")
@ResponseBody  //This annotation is used by ajax to get the return value
public Map<String,Object> update(Long num,BigDecimal amount){
	map<string,Object> resultMap=new HashMap<string,Object>();
	
	if(num==null || agentId==null || amount==null){
		resultMap.put("result","Illegal parameters");
		return resultMap;
	}
	resultMap.put("result",result);
	
}


jquery ajax gets the return value:

var params={};
params.num=num;
params.id=id;
params.amount=amount;
$.ajax({
	async:false,
	type:"post",
	url:"uset/update",
	data:params,
	dataType:"json",
	success:function(data){
		if(data.result=='success'){
			alert('Modified success');
		}else{
			alert('Modification failed');
		}
	},
	error:function(data){
		alert(data.result);
	}
	
})

If the parameters defined in js are consistent with the javabean defined in the persistence layer, the controller layer can also accept entities.


[MUI Binding Data Example]


It's easy to get the JSON value from the controller using jquery, so how do we manipulate the JSON value to bind it to the page control? First, let's briefly understand the structure of json:


         var employees=[{"name":"Jon","age":12},{"name":"Tom","age":14}];


As in the Json object defined above, {} denotes the object, [] denotes the array, "" denotes the attribute or value, "" denotes that the latter is the value of the former.


Get the value in the json object: var name=employees[0].name;


Amendment: employees[0].name="LiMing";


The application example of MUI framework implements adding li tag in list:

mui.init();

var url="queryUser"
mui.ajax(url,{
	data:{
		'type':1,
		'limit':10
	},
	dataType:'json',
	type:'post',
	success:function(data){
		var songs=data.result.songs;
		var list=document.getElementById("list");
		var fragment=document.creeateDocumentFramgment();
		
		var li;
		mui.each(songs,function(index,item){
			var id=item.id,
			name=item.album.name,
			author=item.artists[0].name;
			
			li=document.createElement('li');
			li.className="mui-table-view-cell mui-media";
			li.innerHTML='<a class="mui-navigate-right" id='+ id +' data-audio='+ audio +'>'+'<img class="mui-media-object mui-pull-left" data-lazyload="'+picUrl+'">'+'<div class="mui-media-body">'+name+'<p class="mui-ellipsis">'+author+'</p>'+'</div>'+'</a>';
		fragment.appendChild(li);
		})
		
		list.appendChild(fragment);
		mui(document).imageLazyload({
			placeholder:'../img/60*60.gif';
		});
		
	},erro:function(xhr,type,errorThrown){
		console.log(type);
	}
	
});

//List Click Events
mui("#list").on('tap','li a',function(){
	var id=this.getAttribute('id');
	var audio=this.getAttribute('data-audio');
	mui.openWindow({
		url:'music.html',
		id:'music.html',
		extras:{
			musicId:id,
			audioUrl:audio
		}
	});
});

[Conclusion]


Compared with xml files, data in json format is fast and stable, which is a good choice in front-end design.





Posted by foolguitardude on Mon, 01 Apr 2019 06:18:30 -0700