【问题标题】:AJAX reloads page after POST requestPOST 请求后 AJAX 重新加载页面
【发布时间】:2018-01-21 16:18:02
【问题描述】:

我有一个包含项目列表的页面。我希望能够编辑这些项目。为了实现这一点,我为每个项目添加了一个编辑按钮。单击编辑按钮时,我使用 jquery / AJAX 来获取编辑表单。

这很好用。但是,一旦填写了表单(具有 id="object-create"),我再次想使用 AJAX 将更改发布到我保存它们的后端。

AJAX 发布

$('#object-create').on('submit', function(event){
    event.preventDefault();

    var myform = document.getElementById('object-create');
    var fd = new FormData(myform );
    var post_url = $(this).attr('action');

    $.ajax({
        url : post_url,
        data : fd,
        cache: false,
        processData: false,
        contentType: false,
        type : "POST",
        success : function(data) {
            $('#result-container').html(data)
        },
        error : function() {
            alert("error")
        }
    });
});

但这不起作用,因为我的表单上的 jquery 事件永远不会触发。

当我简单地将表单硬编码到我的页面中时,事件确实会触发,当我在浏览器的 Inspector 中检查它时,我会在旁边看到一个小的“ev”符号

<form enctype="multipart/form-data" action="some_url/" method="post" id="object-create"> 'ev'

当我通过 AJAX GET 请求附加此表单时,它不存在。我猜我必须(重新)将事件绑定到插入的表单,但我不知道如何。我该怎么做呢?

【问题讨论】:

    标签: jquery ajax


    【解决方案1】:

    根据我的理解,页面最初加载时您的表单不存在,而您在页面加载后动态创建表单。

    $('#object-create').on('submit', function(event){ 更改为$(document).on('submit', '#object-create', function(event){。有关更多信息,请阅读event propagation 上的此部分。

    旁白:通过做来简化你的代码

    $(document).on('submit', '#object-create', function (event){
         event.preventDefault();
    
         // "this" is your form
    
         var fd = new FormData(this);
         var post_url = this.action;
         // etc
    });
    

    【讨论】:

      【解决方案2】:

      您似乎正在向表单添加提交事件。

      相反,向表单添加一个按钮,(按钮类型的按钮)它有助于与您不想做的事情保持一致,为按钮添加一个事件并将按钮 id 设置为 button1 .从此按钮中调用您的脚本。表单不应再自行提交。

      这是一个例子,你可以更深入地学习。

      <!DOCTYPE html>
      <html>
      
      <head>
      
          <title>ajax form submit</title>
      
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
      
          <!-- GOOGLE JQUERY JS v3.2.1  JS !-->
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      
          <style type="text/css">
          </style>
      
      </head>
      
      <body>
      
          <script>
              // Loads before document ready...
              $(document).on('click', '#button1', function(e) {
      
                  ajaxPost();
      
                  // Blur button1 for aesthetic reasons.
                  $('#button1').blur();
      
              });
      
      
              $(document).ready(function() {
      
                  console.log('1. Document is ready.');
      
                  // Run the App.
                  runApplication();
      
              });
      
              // We create a variable called runApplication and assign it a function runApplication()
              var runApplication = function runApplication() {
      
                  console.log('1.0 runApplication() function called.');
      
                  // ajax Post.
                  ajaxPost();
      
              };
      
              /* Main AJAX function */
              function ajaxPost() {
      
                  console.log('1.1 ajaxPost() function called.');
      
                  //var data = $('#form1').serializeArray();
                  console.log('2. Encode #form1 set of elements as a Serialized Array of objects (Names & Values)');
      
                  // Serialized Array of objects from #form1.
                  // Simulation purposes ONLY.
                  var data = [{
                          "name": "client_id",
                          "value": "111"
                      },
                      {
                          "name": "project_id",
                          "value": "222"
                      },
                      {
                          "name": "user_id",
                          "value": "465605"
                      }
                  ];
      
                  // data: Serialized Array of objects (Names & Values).
                  console.log(data);
      
                  console.log('3. Stringify this Serialized Array of objects (Names & Values)');
      
                  // Stringify Serialized Array of objects.
                  data = JSON.stringify(data);
      
                  // data: Stringifyed Serialized Array of objects.
                  console.log(data);
      
                  console.log('3.1 data is now Valid JSON (RFC 4627).');
                  console.log('3.2 data to be sent is of type: ' + typeof data);
                  console.log('3.3 data is now ready for AJAX request.');
      
                  $.ajax({
                      url: 'php_pdo_mysql_insert.php', // url to post request to.
                      method: 'POST', // method of request. POST & GET
                      contentType: "application/json; charset=utf-8", // contentType is the type of data you're sending, so application/json; charset=utf-8 for JSON
                      dataType: 'text', // dataType is what you're expecting back from the server: json, html, text.
                      data: data, // data to send. Use encodeURIComponent(data) whenever you want to send "problematic" characters in the URL such as &, % etc. The opposite is decodeURIComponent.
                      timeout: 5000, // Longer than 5 seconds? HTTP SERVER or PHP Offline.***
      
                      // AJAX beforeSend event...
                      beforeSend: function() {
                          console.log('4. Ajax beforeSend* event fired.');
                      },
      
                      // AJAX success event...
                      success: function(data, textStatus, jqXHR) {
      
                          console.log('4.1 Ajax success* event fired.');
      
                          console.log('4.2 data received is of type: ' + typeof data);
      
                          // If data return 1 = Successful Insert Query
                          if (data === 1) {
                              console.log('Status: MySQL Insert Successful.');
                          }
      
                          // If data return 2 = Database Connection refused
                          if (data === 2) {
                              console.log('Status: MySQL Connection Refused.');
                          }
      
                      },
      
                      // AJAX error event...
                      error: function(jqXHR, textStatus, errorThrown) {
                          // If http server and/or PHP is/are offline...
                          if (errorThrown === 'timeout') {
                              console.log('5. Ajax error* event fired.');
                              console.log('5.1 Ajax errorThrown* timeout* of 5 seconds reached.');
                              console.log('5.2 Status: NGINX or PHP offline?');
                          }
      
                      }
                      // AJAX done event...
                  }).done(function() {
      
                      console.log('4.3 Ajax done* event fired.'); // Fired ONLY on success event fire.
      
                      // AJAX fail event...
                  }).fail(function() {
      
                      console.log('5.3 Ajax fail* event fired.'); // Fired ONLY on error event fire.
      
                  });
      
              } // END ajaxPost()
      
              // Loads before document ready...
              $(document).on('click', '#button1', function(e) {
      
                  // Cancel the default action (navigation) of the click.
                  e.preventDefault();
                  // Call ajaxPost() function..
                  ajaxPost();
                  // Blur button1 for aesthetic reasons.
                  $('#button1').blur();
      
              });
          </script>
      
      
          <form id="form1">
      
              Client ID: <input type="text" name="client_id" value="111">
              <br> Project ID: <input type="text" name="project_id" value="222">
              <br> User ID: <input type="text" name="user_id" value="465605">
              <p>
                  <button type="button" id="button1" ">button1</button>
      
      </form>
      
      Check Web Console <strong>Ctrl + Shift + K</strong>
      
      </body>
      
      </html>
      

      【讨论】:

      • 但是当我创建表单时,我仍然需要将事件重新绑定到按钮。
      猜你喜欢
      • 1970-01-01
      • 2016-12-20
      • 1970-01-01
      • 2012-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多