js从后台取值并绑定到元素上

时间:2023-03-08 16:48:08

用ajax从后台取值不是什么有技术含量的活计,把后台取来的值绑定到Vue对象上也不算难,但每一次向后台拿数据的时候都得写上这么一段代码就十分痛苦了。

于是我写了这么一小段js代码,能够自己根据url去后台拿数据,拿来之后自动创建Vue对象并绑定到页面上,整个过程一步到位,岂不美哉!

/**
* 这是一个数据绑定插件,binding()方法接受两个参数,并通过ajax取值然后直接绑定到html元素上<br>
* @author lille 创建于 2019-3-29
*/
var obj = this;
/**
*
* @param elname html元素,通常是一个字符串格式的css选择器,比如:"#t_table"
* @param ajaxpa <br>
* 包含ajax所需的url、data、type,比如:<br>
* <pre>
* {
* url:"getpeoplelist",
* data:{},
* type:"get"
* }
* </pre>
* @returns
*/
function binding(elname, ajaxpa) {
if (typeof (obj[elname]) == "undefined") {
obj[elname] = new Vue({
el : elname,
data : {
data : {}
}
})
obj.callback = function() {
return function(result) {
for ( var key in result) {
Vue.set(obj[elname].data, key, result[key]);
}
}
}
}
$.ajax({
url : ajaxpa.url,
data : ajaxpa.data,
type : ajaxpa.type,
dataType : "json",
success : obj.callback()
})
}

binding.js

在html页面这样调用:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<table id="t_table2">
<tr>
<td>{{data.name}}</td>
</tr>
</table>
<script type="text/javascript" src="static/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="static/vue.min.js"></script>
<script type="text/javascript" src="static/binding.js"></script>
<script type="text/javascript">
binding("#t_table2", {
url : "people",
data : {},
type : "get"
})
</script>
</body>
</html>

NewFile.html

后台代码部分更是简单:

package red.lille.entity;

public class People {
private String name = "张三"; public People() {
} public People(String name) {
// TODO Auto-generated constructor stub
if (name != null) {
this.name=name;
}
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
}
}

People.java

package red.lille.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; import red.lille.entity.People; @Controller
public class AjaxController { @ResponseBody
@RequestMapping("/people")
public People getPeople(@RequestParam(value="name",required=false)String name) {
return new People(name);
}
}

AjaxController.java

最终实现的效果:

js从后台取值并绑定到元素上

话说回来,只看html页面的话还真挺像jsp的EL表达式的