FAj*_*jir 4 java jquery firebug jquery-autocomplete jquery-ui-autocomplete
我尝试使用autocomplete jquery-ui脚本,但是从文档中解释说远程源必须返回一个json数据,它不是在讨论纯文本响应,而是在jsp/servlet中开发我的应用程序而我不知道如何创建json数据.
所以我发现了另一个jquery自动完成插件 - > java自动完成功能
本教程和脚本工作得很好,但脚本没有我需要的相同选项.我尝试保持相同的getdata.jsp和servlet页面以适应jquery-ui-autocomplete只更改脚本的链接,firebug说我对请求的正确响应但是没有显示!
JavaScript调用:
<script>
$(function() {
$( "#responsable" ).autocomplete({
source: "getdata.jsp",
minLength: 2
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
这是getdata.jsp文件:
<%@page import="java.util.Iterator"%>
<%@page import="java.util.List"%>
<%@page import="fr.myldap.model.*"%>
<%
PersonneDB db = new PersonneDB();
String query = request.getParameter("term");
List<Personne> personnes = db.getData(query);
Iterator<Personne> iterator = personnes.iterator();
while(iterator.hasNext()) {
String personne = (String)iterator.next().getNomComplet();
out.println(personne);
}
%>
Run Code Online (Sandbox Code Playgroud)
这是返回人员列表的PersonneDB类
package fr.myldap.model;
import java.util.ArrayList;
import java.util.List;
public class PersonneDB {
private LDAPInterneDao piDao;
private LDAPExterneDao peDao;
public PersonneDB() {
ContextVar var= new ContextVar();
piDao = var.getPiDao();
peDao = var.getPeDao();
}
public List<Personne> getData(String query) {
List<Personne> matched = new ArrayList<Personne>(piDao.findByName(query));
matched.addAll(peDao.findByName(query));
return matched;
}
}
Run Code Online (Sandbox Code Playgroud)
我希望有人能帮助我
首先从这个位置下载java的json库.
现在要返回JSON数据,您需要遵循自己的格式,例如:
{
"firstName": "John",
"lastName": "Smith",
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": 10021
},
"phoneNumbers": [
"212 732-1234",
"646 123-4567"
]
}
Run Code Online (Sandbox Code Playgroud)
如您所见,json数据可以具有键:值对,对象可以存储在内部{ },数组可以存储[ ]等等.
现在要将您的响应转换为JSON对象,您需要在jsp文件中导入以下语句:
import net.sf.json.JSONObject;
Run Code Online (Sandbox Code Playgroud)
(它可能会改变,取决于您正在下载的lib,您可以探索javadoc以获取更多详细信息)
现在看一下下面的代码,创建一个json对象并返回它:
JSONObject object=new JSONObject();
object.put("name","Amit Kumar");
object.put("employeeList",employeeList);
....
....
System.out.println("json object = "+object);
return object;
Run Code Online (Sandbox Code Playgroud)
它会自动将key:value对转换为正确的JSON对象...
更新:
必需的库:
commons-lang 2.3
commons-beanutils 1.7.0
commons-collections 3.2
commons-logging 1.1
ezmorph 1.0.4.jar
json-lib-2.2.2-jdk15.jar
Run Code Online (Sandbox Code Playgroud)
你可以从这里下载所有:
要将arraylist转换为json,请使用以下示例代码:
List mybeanList = new ArrayList();
mybeanList.add(myBean1);
mybeanList.add(myBean2);
JSONArray jsonArray = JSONArray.fromObject(mybeanList);
System.out.println("==== : "+jsonArray);
Map map = new HashMap();
map.put("beanlist", jsonArray);
JSONObject jsonObject = JSONObject.fromObject(map);
return jsonObject;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7819 次 |
| 最近记录: |