java - 在 Java EE 中使用 Ajax 传递 JSON 字符串

标签 java jquery ajax json mongodb

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/

相关文章:

javascript - CSS/jQuery - 响应式设计让关闭按钮留在右上角

javascript - 其中每个变量等于 spans content add class

jquery - 使用 Jquery AJAX 从 ASP.NET Web 服务器获取对象

java - 在 linux 上运行 dmg 程序

c# - 量化垃圾收集与显式内存管理的性能

java - 字符串到 LocalDateTime 转换 : java. time.format.DateTimeParseException

javascript - jQuery:将文件类型类添加到任何文件类型的链接

ajax - 如何使用ajax在Cordova中发送音频文件?

jquery - 使用 jQuery 的异步 ajax 请求会卡住 Chrome

java.util.treemap 给出了奇怪的结果