age*_*rry 10 ajax jquery playframework
我一直在筛选许多jQuery ajax教程,并试图将它与我的Play合并!应用程序,但我不太了解一些事情.是否有人可以通过Ajax调用解释如何执行以下操作:
1)假设我想从控制器中检索联系人列表(每个联系人都有姓名,电话,电子邮件).控制器是否需要为模板"构建"正确的响应?控制器是什么样的?什么是javascript来检索它?
2)通过ajax调用添加/更新新的联系人,javascript是什么样的?
以下是上述解释示例的代码(不使用ajax):
控制器:
public static void list() {
List contacts= Contact.fetchAll();
render(contacts);
}
public static void add(String name, String phone, String email) {
Contact contact = new Contact();
contact.name = name;
contact.phone = phone;
contact.email = email;
contact.save();
}
public static void update(Long id, String name, String phone, String email) {
Contact contact = Contact.findById(id);
contact.name = name;
contact.phone = phone;
contact.email = email;
contact.save();
}
模板(列出所有联系人):
#{list contacts, as:'contact'}
${contact.name}
${contact.phone}
${contact.email}
#{/list}
模板(添加联系人):
#{form @Contacts.add(), id:'form'}
<input type="text" name="name" />
<input type="text" name="phone" />
<input type="text" name="email" />
<input type="submit" value="Add" />
Run Code Online (Sandbox Code Playgroud)
#{/form}
Mik*_*ame 13
我不熟悉Play方面的东西,但如果你想通过Ajax调用检索一些JSON数据,控制器可能看起来像:
public static void getContacts() {
List<Contact> contacts = // get contacts here...
renderJSON(contacts);
}
Run Code Online (Sandbox Code Playgroud)
用于检索JSON数据的jQuery看起来像:
// the getJSON function automatically parses the returned JSON
// data into a JS data structure
$("#retrieve_contacts").click(function(event) {
$.getJSON("/url/which/calls/controller/", function(contacts) {
// do something with contacts list here...
});
});
Run Code Online (Sandbox Code Playgroud)
要添加/更新联系人,您可以执行以下操作:
// call the controller to add the relevant contact with
// the info in the second param:
$("#add").click(function(event) {
var newcontact = {
name: $("input[name='name'").val(),
phone: $("input[name='phone'").val(),
email: $("input[name='email'").val(),
};
$.post("/url/which/adds/new/contact/", newcontact, function(data) {
alert("Contact added!");
});
});
Run Code Online (Sandbox Code Playgroud)
你显然想要添加大量的错误处理.该$.getJSON和$.post功能是更加灵活的快捷方式$阿贾克斯.看看有更多的选择.
| 归档时间: |
|
| 查看次数: |
10746 次 |
| 最近记录: |