简体   繁体   中英

JQuery Ajax POST call not sending parameters correctly

I'm trying to learn Ajax and have some problem with how to send the request from the client.

I have a jsp at "/web" on my local server that handles requests (Not sure if this is best practise, or if it should be handled in a servlet, but it's just a mockup so I guess it's ok). The code for the jsp is like this:

<%!
int i;
public void jspInit() {    
    i = 0;
    System.out.println("Initialized");
}
%>
<html> 
    <head>
        <title>My web page</title>
    </head>
    <body>
        <%
            String content = request.getParameter("content");
            System.out.println("Processed " + content); i++; %>
        <%= "Hello World " + i %> 
        <br>
        You sent me the text: <%= content %>
    </body> 
</html>

and the function for sending the request on client side is:

$("#send").click(function(){
    sentData = {content: "Test data to send"};
        $.post({
            url: '/web',
            data: JSON.stringify(sentData),
            processData: false,
            contentType: "application/json; charset=UTF-8",
            success: function(data) {
            $("#form").html("Sent from client: " + sentData.content + "<br>" + "Recieved from server:<br>" + data);
        },
        error: function(data) {
            $("#form").html("Could not send message.");
        }
    });

This however gives the output

Sent from client: Test data to send
Received from server:
Hello World 2 
You sent me the text: null

on the client, and the System.out.println on the server only writes "Processed null" when the request is sent. I guess I am doing something wrong when sending the data through JQuery.

Sending the data through the URL address "[mydomain]/web/?content=Test+data+to+send" gives the expected output

Hello World 2 
You sent me the text: Test data to send

as does sending a POST request through tools like Postman, so I imagine the server side is set up correctly. What am I doing wrong at the JQuery request? I have also tried some more simple calls like this:

$("#send").click(function() {
    sentData = {content: "Test data to send"};
    $.post({
        url: '/web',
        data: sentData,
        dataType: 'html',
        success: function(data) {
            $("#form").html("Sent from client: " + sentData.content + "<br>" + "Recieved from server:<br>" + data);
        },
        error: function(data) {
            $("#form").html("Could not send message.");
        }
    });
});

with the same result.

Try to send object instead of string:

...
data: {content: "Test data to send"},
dataType: '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