【问题标题】:How to convert XMLHttpRequest() to ajax如何将 XMLHttpRequest() 转换为 ajax
【发布时间】:2017-08-22 22:25:57
【问题描述】:

我通常使用 ajax,但以前从未用它发送文件。我最初的研究表明您无法使用 ajax 发送文件,所以我找到并使用了这种方法;但后来的研究表明可以使用 ajax 发送文件。

现在我担心更改它,因为目前一切正常,但我仍然不明白 html/jscript 如何处理文件。所以我想知道,如何将这个函数转换为Ajax,而不需要我更改来更改upload_metric_post.php 代码?

function uploadMetric(file){
    var MetricID = $("#MetricID").val();
    var ReportPeriod = $("#ReportPeriod").val();
    if(MetricID == ""){
        $("#upload_results").addClass("alert-danger");
        $("#upload_results").removeClass("alert-success");
        $("#upload_results").html("Please select the MetricID before uploading.");
    }else{
        var url = 'php/upload_metric_post.php';
        var xhr = new XMLHttpRequest();
        var fd = new FormData();
        xhr.open("POST", url, true);
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                // Request went thru ok, handle response.
                var response = xhr.responseText;
                console.log(response);
                var jsonResponse = JSON.parse(response);

                if(jsonResponse["success"] == false){
                    var errors = jsonResponse["msg"] + jsonResponse["error"];
                    $("#upload_results").addClass("alert-danger");
                    $("#upload_results").removeClass("alert-success");
                    $("#upload_results").html(errors);
                    $("#dropped_rows_panel").html(jsonResponse["bad_rows"]);
                    $("#start_over_btn").show();
                    $("#process_btn").hide();
                }else if(jsonResponse["success"] == true){
                    $("#upload_results").addClass("alert-success");
                    $("#upload_results").removeClass("alert-danger");
                    $("#upload_results").html(jsonResponse["msg"]);
                    $("#dropped_rows_panel").html(jsonResponse["bad_rows"]);
                    $("#start_over_btn").show();
                    $("#process_btn").show();
                }
            }
        };
        fd.append("MetricID", MetricID);
        fd.append("ReportPeriod", ReportPeriod);
        fd.append("upload_file", file);
        xhr.send(fd);
    }
}

这是我在整个代码中使用的标准,以前从未发送过文件,我真的不知道如何将其转换为我的标准:

function get_assets(display_qty, go_page, sorts, sorts_order, filters_ordered, CallBack) {
    $.ajax({
        method: "POST",
        url: "php/assets_post.php",
        data: {
            display_qty: display_qty,
            go_page: go_page,
            sorts: sorts,
            sorts_order: sorts_order,
            filters_ordered: filters_ordered
        },
        success: function(result){
            CallBack(result);
        },
        error: function(result){
            CallBack(result);
        }
    });
}

【问题讨论】:

  • 不要重新发明轮子dropzonejs.com
  • 有类似的问题,如果你先看看它会对你有所帮助。这是链接stackoverflow.com/questions/10654429/…
  • 看起来两种方式都使用 AJAX 来处理请求。 xhr.open 等是编写 AJAX 调用的普通 JavaScript 方式。您使用 $.ajax 列出的方法是 jquery 方法。我喜欢它,它更干净,所以我通常用 jquery 编写我的,但他们做同样的事情,所以如果它现在可以工作......

标签: javascript php jquery ajax xmlhttprequest


【解决方案1】:

XMLHttpRequest 和 AJAX 是一回事。您所指的 Ajax 可能是 jQuery 的名为 ajax 的函数,用于实现对服务器端点的异步调用。 jQuery 实际上包装了 XMLHttpRequest 对象。

【讨论】:

    【解决方案2】:

    即使您的代码是 ajax,如果正在为您的代码寻找 jquery ajax 语法,只需执行以下操作:

    $.ajax({ method: "POST", url: "php/upload_metric_post.php", }) .done(function(data, textStatus, jqXHR) { var response = xhr.responseText; console.log(response ); var jsonResponse = JSON.parse(response); ---其余相同--- });

    【讨论】:

      【解决方案3】:

      这是最终的解决方案,它依赖于将数据作为 FormData 对象发送到 ajax。 contentType 和 processData 设置至关重要,因为没有它们就无法工作;为什么没有它们就不行我不知道:

      function uploadMetric(file){
          var MetricID = $("#MetricID").val();
          var ReportPeriod = $("#ReportPeriod").val();
          if(MetricID == ""){
              $("#upload_results").addClass("alert-danger");
              $("#upload_results").removeClass("alert-success");
              $("#upload_results").html("Please select the MetricID before uploading.");
          }else{
              var fd = new FormData();
              fd.append("MetricID", MetricID);
              fd.append("ReportPeriod", ReportPeriod);
              fd.append("upload_file", file);
              $.ajax({
                  method: "POST",
                  url: "php/upload_metric_post.php",
                  data: fd,
                  contentType: false,
                  processData: false,
                  success: function(result){
                      console.log(result);
                      var jsonResponse = JSON.parse(result);
                      if(jsonResponse["success"] == false){
                          var errors = jsonResponse["msg"] + jsonResponse["error"];
                          $("#upload_results").addClass("alert-danger");
                          $("#upload_results").removeClass("alert-success");
                          $("#upload_results").html(errors);
                          $("#dropped_rows_panel").html(jsonResponse["bad_rows"]);
                          $("#start_over_btn").show();
                          $("#step3_intructions").html(errors + "<br />Please check your file, fix any errors and start over.");
                          $("#step3_intructions").addClass("alert-danger");
                          $("#step3_intructions").removeClass("alert-success");
                          $("#step3_intructions").show();
                          $("#process_btn").hide();
                      }else if(jsonResponse["success"] == true){
                          $("#ReportPeriod").attr('disabled','disabled');
                          $("#MetricID").attr('disabled','disabled');
                          $("#fileinput").attr('disabled','disabled');
                          $("#fileinput_label").attr('disabled','disabled');
                          $("#upload_results").addClass("alert-success");
                          $("#upload_results").removeClass("alert-danger");
                          $("#upload_results").html(jsonResponse["msg"]);
                          $("#dropped_rows_panel").html(jsonResponse["bad_rows"]);
                          $("#start_over_btn").show();
                          $("#step3_intructions").html("<p>Please review any dropped rows. If there are no dropped rows and you are ready to process the metric, press 'Process Metric'. If there are dropped rows you have the following options:<p><ol><li>Correct the rows in the original file you uploaded, re-upload and check the dropped rows again or,</li><li>if you are okay with the dropped rows you may process the accepted rows anyway.</li></ol>");
                          $("#step3_intructions").addClass("alert-success");
                          $("#step3_intructions").removeClass("alert-danger");
                          $("#step3_intructions").show();
                          $("#process_btn").show();
                      }
                      CallBack(result);
                  },
                  error: function(result){
                      alert("mm");
                      CallBack(result);
                  }
              });
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-14
        • 2021-12-29
        • 1970-01-01
        • 1970-01-01
        • 2017-10-21
        • 2012-02-08
        相关资源
        最近更新 更多