简体   繁体   中英

jQuery ajax POST is sending an additional GET request

I am just starting with jQuery and I am trying to do a $.post request, but I am getting a post AND a get (see log below). I have searched a lot and only found cases where they were calling an ajax function twice.

My case is a dynamic table of forms where I want to send an ajax POST when a single form is submitted.

Here is my javascript:

$(document).on('submit', 'form.newguess', function (event) {
    event.preventDefault();
    alert($(this).serialize());
    $.post("game", $(this).serialize());
});

Here is my JSP:

...<tbody>
    <c:forEach var="player" items="${players}">
        <tr>
            <td class="namecell"><p>${player.key}</p></td>
            <td class="guesscell">
                <p>${player.value}</p>
            </td>
            <td class="inputcell">
                <form class="newguess" action="game" method="post">
                    <input type="text" name="guess" />
                    <input type="hidden" name="player" value="${player.key}"/>
                    <input type="submit" value=">"/>
                </form>
            </td>
        </tr>
    </c:forEach>
</tbody>

And here is the log from my server:

23:32:41,617 INFO (http-localhost/127.0.0.1:8080-3) POST - Game
23:32:41,696 INFO (http-localhost/127.0.0.1:8080-3) GET - Game

I have tried to remove the $.post and then I don't receive anything, so it is definitely the $.post.

Any ideas are welcome, it must be a very dumb mistake.

Thank you.

I think you can use a normal button instead of

<input type="submit" value=">"/>

use

<input type="button" value=">" onclick="yourFunction"/>

Maybe thats why it is sending two times, one from jquery and another from the DOM (?)

Solved it! I knew it had to be something dumb.

This is my code on the server:

@RequestMapping(value = "/game", method = RequestMethod.POST)
public String postPlayerGuess(@RequestParam("player") String playerName,
          @RequestParam("guess") String guess, Model model) {
    System.out.println("POST");
    gameService.setGuess(myself.getGameName(), playerName, newGuess);
    return "redirect:/game";
}

Notice that redirect:/game at the end? yep, that it was. I was redirecting the response, so the client made another GET request.

Sorry guys, you couldn't have solved this one without the code on the server, my bad!

It is due to, you have put your form in loop. So that every first iteration your mentioned form method will post but after that all form will have get request by default.

You need to generate unique "name" for every form . To avoid multiple GET/POST request .

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