【问题标题】:jQuery mobile and JSON post responsesjQuery 移动和 JSON 发布响应
【发布时间】:2011-11-14 19:30:36
【问题描述】:

处理返回 json 响应的表单帖子的最佳做法是什么?我们正在尝试在我们网站的移动版本中重用一些返回 JSON 的代码,我不确定处理 javascript 的最佳方式。我想填充一个对话框。我真的必须在表单标签上将 data-ajax 设置为 false 并改为调用 $.post 吗?

谢谢, 抢

【问题讨论】:

    标签: jquery jquery-mobile


    【解决方案1】:

    是的,为了在 jQuery Mobile 中处理表单提交,您必须将 data-ajax="false" 添加到表单标签,这样 jQuery Mobile 框架就不会为您处理它。然后,您可以为 submit 事件设置自己的处理程序:

    //add event handler to your form's submit event
    $('form').on('submit', function (e) {
        var $this = $(this);
    
        //prevent the form from submitting normally
        e.preventDefault();
    
        //show the default loading message while the $.post request is sent
        $.mobile.showPageLoadingMsg();
    
        //send $.post request to server, `$this.serialize()` adds the form data to the request
        $.post($this.attr('action'), $this.serialize(), function (response) {
    
            //you can now access the response from the server via the `response` variable
            $.mobile.hidePageLoadingMsg();
        }, 'json');//you can set the response data-type as well
    });
    

    这是$.post() 的文档:http://api.jquery.com/jquery.post/

    注意:.on() 用于代替已折旧的.bind() 函数:http://api.jquery.com/on/

    【讨论】:

      【解决方案2】:

      您可能希望在 Jasper 的示例中添加一个 .error() 处理程序,否则如果 jquery 或服务器端出现错误,您的加载消息将保持在顶部,直到用户刷新页面,这可能会导致很多他输入的数据。

      //add event handler to your form's submit event
      $('form').on('submit', function (e) {
          var $this = $(this);
      
          //prevent the form from submitting normally
          e.preventDefault();
      
         //show the default loading message while the $.post request is sent
          $.mobile.showPageLoadingMsg();
      
          //send $.post request to server, `$this.serialize()` adds the form data to the request
          $.post($this.attr('action'), $this.serialize(), function (response) {
      
              //you can now access the response from the server via the `response` variable
              $.mobile.hidePageLoadingMsg();
          }, 'json') //you can set the response data-type as well
          .error(function(e) {
              $.mobile.showPageLoadingMsg();
              console.log('my_function_name, ' + e.responseText); 
          });
      });
      

      【讨论】:

        【解决方案3】:

        这篇文章对你有帮助吗?

        http://www.giantflyingsaucer.com/blog/?p=2574

        也许您可以再解释一下,“我真的必须在表单标签上将 data-ajax 设置为 false”是什么意思?如果您想保留 AJAX 方式,我认为您必须使用例如 $.post 或 $.ajax 处理表单 POST(参见示例)

        【讨论】:

          猜你喜欢
          • 2017-11-13
          • 2023-02-24
          • 2014-06-14
          • 1970-01-01
          • 1970-01-01
          • 2014-12-22
          • 2013-11-24
          • 1970-01-01
          • 2011-01-24
          相关资源
          最近更新 更多