MongoDB 没有内置的 RESTFul 接口(interface),因此我尝试将 MongoDB 查询结果转换为字符串格式并使用 Ajax 发送它,但它给了我一个错误
ServletDemo.java:com.mongodb.servlets
public void doPost(...){
returnString();
}
public String returnString(){
MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
DB database = mongoClient.getDB("db");
DBCollection collection = database.getCollection("coll");
DBObject getDocs = new BasicDBObject();
DBCursor cursor = collection.find(getDocs);
while(cursor.hasNext()){
returnString += String.format("%s",cursor.next());
}
return returnString;
}
index.html
<body>
<button>Click Me</button>
<p></p>
<script>
$(document).ready(function(){
$("button").on("click",function(){
$.ajax({
url:'ServletDemo',
type:'post',
success:function(data) {
alert("Success");
$('p').html(data);
},
error:function(msg){
alert("Error");
console.log(msg);
}
});
});
});
</script>
</body>
最佳答案
ServletDemo.java 中的更改
使用response.getWriter()将数据传递给Ajax调用
public void doPost(...){
MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
DB database = mongoClient.getDB("db");
DBCollection collection = database.getCollection("coll");
DBObject getDocs = new BasicDBObject();
DBCursor cursor = collection.find(getDocs);
while(cursor.hasNext()){
returnString += String.format("%s",cursor.next());
}
response.getWriter().write(returnString);
}
现在工作顺利...
关于java - 在 Java EE 中使用 Ajax 传递 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29802889/