简体   繁体   中英

Sending form data to restful web service @POST method using jquery and ajax

I have looked everywhere for hours and cannot find a solution that will work for me. I have a simple html form that gets 3 form inputs and needs to send the data to the @POST method of a web service. After creation, the web service will show the updated list. Can anyone tell me what I am doing wrong?

poll.html

    <script>

    function myFunction()
    {
        data = $(this).serialize(); 

        $.ajax({
            url:         'http://localhost:8080/places3/resourcesC/create',
            method:      'POST',
            dataType:    'text',
            data:       data,
            success:        function() { alert("Worked"); },
            error:      function(error) { alert("Error"); }
        });
    }

    </script>

  </head>
  <body>
    <form onsubmit="myFunction()">

        <p>City: <input type="text" name="city" /> </p>
        <p>POI1: <input type="text" name="poi1" /> </p>
        <p>POI2: <input type="text" name="poi2" /> </p>
        <input type="submit" value="Submit" />


    </form>

@POST method of web service

@POST
@Produces({MediaType.TEXT_PLAIN})
@Path("/create")
public Response create(@FormParam("city") String city, 
           @FormParam("poi1") String poi1,
        @FormParam("poi2") String poi2) {
checkContext();
String msg = null;
// Require both properties to create.
if (city == null || poi1 == null || poi2 == null) {
    msg = "Property 'city' or 'poi1' or 'poi2' is missing.\n";
    return Response.status(Response.Status.BAD_REQUEST).
                                       entity(msg).
                                       type(MediaType.TEXT_PLAIN).
                                       build();
}       
// Otherwise, create the Place and add it to the collection.
int id = addPlace(city, poi1, poi2);
msg = "Place " + id + " created: (city = " + city + " poi1 = " + poi1 + " poi2 = " + poi2 + ").\n";
return Response.ok(msg, "text/plain").build();
}

I would try giving the form a name such as myform then in your jquery something like:

var data = $("#myform").serializeArray();

Then pass the data var in the ajax command.

This works perfectly for me.

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