使用HTML表单的请求正文发出发布请求

时间:2017-08-13 17:56:10

标签: javascript jquery html forms post

我正在开发一个html页面,它应该向我的服务器提交一个请求正文的帖子请求,如下所示

<html>
    <head>Customer app</head>
    <body>
         <div> 
             <table> 
                 <tr>
                     <td>Customer Id :</td> 
                     <td>
                         <form name="submitform" method="post">
                             <input type="text" id="customerId" name="customerId"/>
                             <input type="submit" value="Submit">
                         </form>
                     </td>
                 </tr>
             </table>
        </div>
    </body>

    <script>
    $(document).ready(function(){
        $("#submitform").click(function(e)
        {
            var MyForm = JSON.stringify($("#customerId").serializeJSON());
            console.log(MyForm);
            $.ajax({
                url : "http://localhost:7777/ola-drive/customer/ride",
                type: "POST",
                data : MyForm,

            });
            e.preventDefault(); //STOP default action

        });
    });
    </script>
</html>

它无法正常工作,将404 Not Found重定向到http://localhost:7777/customerapp.html。但是与请求提交相对应的表单数据似乎是正确的。

有人可以帮我修复我的html代码提交POST请求重定向的问题吗?

3 个答案:

答案 0 :(得分:2)

您的问题在这一行:

$("#submitform").click(function(e)

您的表单没有ID而是名称,因此您可以写:

$('[name="submitform"]').click(function(e)

这就是原因,因为你的表单给你一个重定向错误。

&#13;
&#13;
$('[name="submitform"]').click(function (e) {
    e.preventDefault(); 
    $.ajax({
        url: "http://localhost:7777/ola-drive/customer/ride",
        type: "POST",
        data: {"customerId": $("#customerId").val()},
        success: function (result) {
            //do somthing here
        }
    });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div>
    <table>
        <tr>
            <td>Customer Id :</td>
            <td>
                <form name="submitform" method="post">
                    <input type="text" id="customerId" name="customerId"/>
                    <input type="submit" value="Submit">
                </form>
            </td></tr>
    </table>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您已经使用html创建了表单,您可以添加操作 attrbiute以及发布网址的值

// Will return a row with EM10002's password, which is 'hashed_pass2'. 
SELECT Password from Admins WHERE IdEmployee = EM10002

除非您想使用ajax,否则您需要手动创建数据表单

答案 2 :(得分:-1)

你有这个:

 $("#submitform").click(function(e){...}

第一个问题是您正在选择输入标签,而不是表格。第二个是所需的行动,在这种情况下应该是“提交”。如果你已经在使用JQuery,你可能会对使用'serialize()'方法保存一些空间感兴趣。尝试:

$('form').on('sumbit', function(e){
  e.preventDefault();
  $.ajax({
    url: // your path
    type: 'post',
    data: $(this).seialize(),
    ...})
 })

使用Form的id,更容易选择它。

相关问题