【问题标题】:AJAX Form Submission in jQuery MobilejQuery Mobile 中的 AJAX 表单提交
【发布时间】:2011-12-22 04:50:38
【问题描述】:

我正在尝试在 jQuery Mobile 网站上通过 ajax 提交一个简单的登录表单,但遇到了问题。

似乎当我提交表单(通过 POST)时,表单参数被添加到 url。不仅如此,他们还删除了我在提交表单之前所在的锚定页面。

例如,我在页面localhost:8080/myapp/#sign_up

然后我提交表单导致 url 变为:localhost:8080/myapp/?email=a@a.com&pass=pass

因此,如果我遇到验证错误并单击“返回”按钮,我不会返回到 #sign_up 页面。

有什么想法吗?

【问题讨论】:

    标签: jquery-mobile jquery-validate ajaxform


    【解决方案1】:

    如果您使用自定义 submit 事件处理程序处理表单提交,您可以在同一页面上处理验证:

    //bind an event handler to the submit event for your login form
    $(document).on('submit', '#form_id', function (e) {
    
        //cache the form element for use in this function
        var $this = $(this);
    
        //prevent the default submission of the form
        e.preventDefault();
    
        //run an AJAX post request to your server-side script, $this.serialize() is the data from your form being added to the request
        $.post($this.attr('action'), $this.serialize(), function (responseData) {
    
            //in here you can analyze the output from your server-side script (responseData) and validate the user's login without leaving the page
        });
    });
    

    要阻止 jQuery Mobile 运行自己的表单 AJAX 合并,请将其放在表单标签上:

    <form data-ajax="false" action="...">
    

    【讨论】:

    • 对反对票的任何反馈将不胜感激。我只是想知道我做错了什么:)
    • 我也会 ;-) 唯一的可能是现在不推荐使用“live”,您应该改用“on”。甚至可能按顺序“开/关”以防止重复事件:stackoverflow.com/questions/9067259
    【解决方案2】:

    上面的 Jaspers 解决方案对我有用!我唯一需要调整的是将 .live 替换为 .submit (.live 现在已弃用)。所以现在是这样的:

    $('#form_id').submit(function (e) {
    
        //cache the form element for use in this function
        var $this = $(this);
    
        //prevent the default submission of the form
        e.preventDefault();
    
        //run an AJAX post request to your server-side script, $this.serialize() is the data from your form being added to the request
        $.post($this.attr('action'), $this.serialize(), function (responseData) {
    
            //in here you can analyze the output from your server-side script (responseData) and validate the user's login without leaving the page
        });
    });
    

    【讨论】:

    • 关于此的说明,如果表单作为外部页面被拉入 DOM,则必须在此之后运行。这就是为什么我建议使用委托事件处理程序的原因,因此即使在初始页面加载后将表单添加到 DOM 中,事件处理程序也会捕获事件。
    【解决方案3】:

    如果您想提交表单而不使用 ajax(这是默认设置),您必须在表单字符串中添加 'data-ajax="false"':

     <form data-ajax="false" action="test.php" method="POST">
    

    【讨论】:

    • 这是上面答案的一部分,介意我问你为什么重新发布它?
    猜你喜欢
    • 1970-01-01
    • 2013-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    • 2011-04-23
    • 2012-04-05
    相关资源
    最近更新 更多