简体   繁体   中英

Pass JSON String using Ajax in Java EE

MongoDB doesn't have a built-in RESTFul Interface so I am trying to convert MongoDB Query Result into a String Format and send it over using Ajax but it is giving me an error

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>

changes in ServletDemo.java

Pass the data using response.getWriter() to Ajax Call

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);
}

Working Successfully now...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM