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

Aar*_*esh 5 html javascript forms jquery post

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

<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>
Run Code Online (Sandbox Code Playgroud)

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

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

gae*_*noM 4

您的问题在这一行:

$("#submitform").click(function(e)
Run Code Online (Sandbox Code Playgroud)

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

$('[name="submitform"]').click(function(e)
Run Code Online (Sandbox Code Playgroud)

这就是原因,因为您的表单给您带来了重定向错误。

$("#submitform").click(function(e)
Run Code Online (Sandbox Code Playgroud)
$('[name="submitform"]').click(function(e)
Run Code Online (Sandbox Code Playgroud)