我正在尝试简单的把手。 最初我尝试使用静态Javascript数组对象来处理车把数据,它运行正常。 所以我尝试使用Javascript Array对象作为来自Java RestURL的JSON字符串(以使把手数据动态化)并编译把手。我通过AJAX调用从RestURL获取数据,甚至模板也是从把手构建的。真正的问题是调用模板函数时,它不会生成带模板的响应数据。 以下是HTML代码:
<html>
<head>
<title>Handlebars.js Demo</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"> </script>
<script src="js/handlebars.js"> </script>
<script id="some-template" type="text/x-handlebars-template">
<table>
<thead>
<th>id</th>
<th>username</th>
<th>password</th>
</thead>
<tbody>
{{#Users}}
<tr>
<td>{{id}}</td>
<td>{{username}}</td>
<td>{{password}}</td>
</tr>
{{/Users}}
</tbody>
</table>
</script>
</head>
<body>
<div id="content"></div>
<script>
$(document).ready(function()
{
$.ajax({
url:"http://localhost:8082/Backbone/rest/test/test1",
method:'get',
success:function (results)
{
var source = $("#some-template").html();
var template = Handlebars.compile(source);
$("#content").html(template(result));
}
})
});
</script>
</html>
&#13;
java Rest代码:
@Path("/test")
public class Common
{
@GET
@Path("/test1")
public Response getMsg()
{
Users user=new Users(1,"harish","ram");
String output=toJson(user);
return Response.status(200).entity(output).build();
}
public String toJson(Object object)
{
Gson gson=new Gson();
String str=gson.toJson(object);
return str;
}
}
用户类:
public class Users
{
private int id;
private String username;
private String password;
public Users(int id,String username, String password){
this.id=id;
this.username = username;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id){
this.id = id;
}
public String getUsername(){
return username;
}
public void setUsername(String username){
this.username = username;
}
public String getPassword(){
return password;
}
public void setPassword(String password){
this.password = password;
}
}
请帮我解决这个问题。
答案 0 :(得分:0)
我通过更改RestURL解决了这个问题,如下所示
@GET
@Path("/test1")
@Produces(MediaType.APPLICATION_JSON)
public JSONObject getMsg() throws JSONException
{
String output ="{ users: [{username: \"alan\", firstName: \"Alan\", lastName: \"Johnson\", email: \"alan@test.com\" },{username: \"allison\", firstName: \"Allison\", lastName: \"House\", email: \"allison@test.com\" },{username: \"ryan\", firstName: \"Ryan\", lastName: \"Carson\", email: \"ryan@test.com\" }]};";
JSONObject obj = new JSONObject();
obj.put("id", 3);
obj.put("userName", 1);
obj.put("password", 2);
return obj;
}