【问题标题】:Sending form data to restful web service @POST method using jquery and ajax使用 jquery 和 ajax 将表单数据发送到 RESTful Web 服务 @POST 方法
【发布时间】:2016-04-19 20:43:05
【问题描述】:

我已经到处找了好几个小时,但找不到适合我的解决方案。我有一个简单的 html 表单,它获取 3 个表单输入,并且需要将数据发送到 Web 服务的 @POST 方法。创建后,Web 服务将显示更新后的列表。谁能告诉我我做错了什么?

投票.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方法

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

【问题讨论】:

  • 目前发生了什么?成功或错误功能是否触发?控制台有错误吗?
  • 它不应该警告错误。它应该在 Ajax 请求解决之前提交表单。
  • 它警告“错误”并且什么都不做,但 url 确实得到了字符串
  • localhost:8080/ajax/?city=flint&poi1=UofM&poi2=MottCC
  • 尝试从错误中获取更好的信息。类似error: function(jqXHR, textStatus, errorThrown){console.log('jqXHR.status: " + jqHR.status); console.log('textStatus: " + textStatus); console.log('errorThrown: " + errorThrown); }

标签: jquery ajax


【解决方案1】:

我会尝试给表单起一个名称,例如 myform 然后在你的 jquery 中类似:

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

然后在ajax命令中传递data var。

这对我来说非常适合。

【讨论】:

    猜你喜欢
    • 2018-10-13
    • 2015-06-11
    • 1970-01-01
    • 2017-05-07
    • 2011-10-30
    • 1970-01-01
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    相关资源
    最近更新 更多