我使用一个简单的json列表创建了这个servlet:
public void aggiungiCategoria(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
logger.log(Level.INFO, "Aggiungo la categoria");
ObjectifyService.register(Studente.class);
ObjectifyService.register(Categoria.class);
String idS=req.getParameter("ids");
String idC= req.getParameter("idc");
Studente s=ofy().load().type(Studente.class).id(Long.parseLong(idS)).now();
System.out.println(s.getNome());
if(s!=null){
Categoria c=ofy().load().type(Categoria.class).id(Long.parseLong(idC)).now();
System.out.println(Key.create(Categoria.class, c.id));
s.addCategoria(Key.create(Categoria.class, c.id));
ofy().save().entity(s).now();
StringBuilder sb= new StringBuilder();
// sb.append("[");
for(Key k : s.getCategorie()){
Categoria c1=ofy().load().type(Categoria.class).filterKey(k).first().now();
System.out.println(c1.getNome());
sb.append("{");
sb.append("id: ");
sb.append("'"+c1.getId()+"', ");
sb.append("nome: ");
sb.append("'"+c1.getNome()+"'},");
}
sb.append("{}");
System.out.println("Aggiunto: "+sb.toString());
resp.setContentType("application/json"); // Set content type of the response so that jQuery knows what it can expect.
resp.setCharacterEncoding("UTF-8");
resp.getWriter().write(sb.toString());
}
}
数据库中只有一个项目的示例输出是:
{id:'4749890231992320',nome:'c2'},{}
在我的javascript代码中,有一个右键菜单点击表格。当用户添加表的项时,启动ajax请求,如果成功使用servlet的数据更新另一个表。
<script type="text/javascript">
$(document).ready(function(){
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
console.log();
$('#contacts tbody tr').contextMenu('myMenu1', {
bindings: {
'open': function(t) { AddAction(t, "Open"); },
'email': function(t) { ShowAction(t, "Email"); },
'save': function(t) { ShowAction(t, "Save"); },
'delete': function(t) { ShowAction(t, "Delete"); }
}
});
function AddAction(t, a) {
$.ajax({
url : 'studenteServlet? action=aggiungiC&ids='+$.urlParam('id')+'&idc='+t.id,
type : "POST",
async : false,
success : function(data) {
console.log(data);
$('#catAssociate tbody > tr').remove();
var html = '';
for(var i = 0; i < data.length; i++)
html += '<tr><td id='+data[i].id +'>' + data[i].nome + '</td></tr>';
$('#catAssociate').append(html);
}
});
}
function ShowAction(t, a) {
alert('Trigger was ' + t.id + '\nAction was ' + a + "\nHtml is " + $(t).html());
} });
如果我用“text / html”更改内容类型,则会发送数据。我使用这个example谢谢你做了这个例子。
编辑 - 我解决了:
sb.append("[");
for(Key k : s.getCategorie()){
Categoria c1=ofy().load().type(Categoria.class).filterKey(k).first().now();
sb.append("{");
sb.append("\"" +"id" + "\" : \"" + c1.getId() + "\",");
sb.append("\"" +"nome" + "\" : \"" + c1.getNome() + "\",");
sb.deleteCharAt(sb.lastIndexOf(","));
sb.append("},");
}
sb.deleteCharAt(sb.lastIndexOf(","));
sb.append("]");
但现在我有画桌子的问题。它在网页上没有标记。
答案 0 :(得分:0)
我编辑了我的答案。这个例子现在工作正常!