2

这是我的表格:

<form id="login_form">
    <table border="0">
        <tr>
            <td>username: </td>
            <td colspan="10">
                <input id="username" name="username" type="text" />
            </td>
        </tr>
        <tr>
            <td>password: </td>
            <td>
                <input id="passwd" name="passwd" type="password" />
            </td>
        </tr>
        <tr style="text-align:center">
            <td>
                <input id="login_submit" type="submit" title="submit" />
            </td>
            <td>
                <input type="reset" title="reset" />
            </td>
        </tr>
    </table>
</form>

我的jQuery代码:

$(function(){
    jQuery("#login_submit").click(function() {
        jQuery.ajax({
            url:'./login/',
            type:'post',
            data:$("#login_form").serialize(),
            dataType:'html',
            async: false,
            success:function(backData)    {
                alert(data);
            },
            error:function(err){
                alert('error = ' + err);
            }
        });
    });
}); 

我感到困惑的是,当我访问 url: 时http://192.168.0.3/CarKeeperServer/user/login.jsp,单击提交按钮(该页面不会定向到新页面,因为 jquery 代码片段中没有重定向代码),并且 url 将更改为http://192.168.0.3/CarKeeperServer/user/login.jsp?username=df&passwd=sd,这是exposes我的用户名和密码就像在GET方法中一样。谁能解释为什么会发生这种情况以及解决方案是什么?非常感谢!

4

1 回答 1

5

您需要通过调用 preventDefault 来阻止表单提交。您看到触发获取请求的原因是您没有阻止表单提交,即提交到您所在的当前页面。

默认情况下,表单使用该get方法将信息发送到服务器。见:http ://www.w3.org/TR/html401/interact/forms.html#adef-action

由于表单没有指定默认动作,它使用当前页面作为动作。这不是设计到 HTML 规范中的,而是由许多浏览器实现以维护遗留应用程序。请参阅:对 HTML 表单的 action 属性使用空 URL 是一种好习惯吗?(动作="")

$(function(){
    jQuery("#login_submit").click(function(e) {
        jQuery.ajax({
            url:'./login/',
            type:'post',
            data:$("#login_form").serialize(),
            dataType:'html',
            async: false,
            success:function(backData)    {
                alert(data);
            },
            error:function(err){
                alert('error = ' + err);
            }
        });
        e.preventDefault();
    });
}); 
于 2013-04-19T08:03:58.207 回答