简体   繁体   中英

Java can not receive data from AJAX POST

I am a newbie of jquery. I am testing a very simple example. Server side (use java) receives data from client side, print it at console. Then response to client side another string.

At client side, I use:

 $.ajax({ type: "POST", url: "http://localhost:8080/", data: { Name: "sanmao", Password: "sanmaoword" }, contentType: "application/json; charset=utf-8", dataType: "jsonp", jsonp: "jsonpcallback", jsonpCallback: "bc", success: function(response) { alert(response[0].name + " " + response[1].name); //$("#msg").html(decodeURI(data)); }, error: function() { } ); 

At servcer side, I use:

InputStream is = exchange.getRequestBody();
        BufferedReader in = new BufferedReader(new InputStreamReader(is));

        String temp = "";
        try {

            // s = ArticleExtractor.INSTANCE.getText(in);
            temp = in.readLine();
            System.out.println("client request: " + temp);
        } catch (IOException e) {
            System.out.println("Processing failed");
        }

        Headers responseHeaders = exchange.getResponseHeaders();

        responseHeaders.set("Content-Type", "text/plain");

        OutputStream responseBody = exchange.getResponseBody();
        String s = "bc([{\"lng\":\"" + lng1 + "\",\"lat\":\"" + lat1 + "\",\"name\":\"" + name1 + "\"},{\"lng\":\""
                + lng2 + "\",\"lat\":\"" + lat2 + "\",\"name\":\"" + name2 + "\"}])";
        exchange.sendResponseHeaders(200, 0);
        responseBody.write(s.getBytes());
        responseBody.close();

But it does not work. If I remove the "data:..." and "contentType...". Client side can receive the response string. But server side can not receive the inbound string.

Can anybody tell me why?

jQuery can't create JSON for you. You have to manually convert the object yourself. You can use JSON.stringify :

data: JSON.stringify({
    Name: "sanmao",
    Password: "sanmaoword"
}),

When you pass an object as the data without doing this, jQuery simply converts it to a list of key value pairs which is sent in the post (in format key1=val1&key2=val2... instead of JSON).

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