WordPress使用jQuery上传ajax文件

时间:2018-01-16 07:43:35

标签: javascript php jquery ajax wordpress

我有一个简单的文件上传ajax请求到admin-ajax.php。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div class="container">  
  <form id="contact" action="" method="post">
    <h3>ROI Calculator</h3>
    <fieldset>
     <font class="label">How many people do you want to save per month? </font>  <input placeholder="" id="active-member" type="text" style="width:110px;float: right;"/>
    </fieldset>
    <fieldset>
      <font class="label">Average Order Size($) </font> <input placeholder="" type="text" id="avg-order-size" style="width:110px;float: right;"/>
    </fieldset>
    <fieldset>
      <font class="label">What percentage of the saved reps will recruit 1 person that month?(%) </font> <input placeholder="10" type="text" id="mem-retain-per-month" onCopy="return false" onPaste="return false" autocomplete=off min="1" max="100" style="width:110px;float: right;"  />
    </fieldset>
    <fieldset>
      <button name="submit" type="button" id="contact-submit" onclick="myFunction();">Clear</button>
      <button name="submit" type="button" id="contact-submit" onclick="myCalculator();" style="float: right;">Calculate</button>
    </fieldset>

   </form>
   </div>

   <div style="margin: 0 auto;width: 100%;">

   <div class="container2" style="display:none;">
   <div id="contact" class="contact2">

   <fieldset>
     <font class="label"> Cumulative Retention Revenue After 12 Months = </font>  

     <span id="value" ></span>
     <div ></div>
    </fieldset>


   </div>
   </div>
   </div>
   <script>
function myFunction() {
    document.getElementById("contact").reset();
}

function myCalculator() {

    var actMem = document.getElementById("active-member").value;
    var avgOrd = document.getElementById("avg-order-size").value;
    var menRetainPM = document.getElementById("mem-retain-per-month").value;


    if(actMem >=1 && actMem<=1000000 && actMem != NaN) { }
    else {  alert("Active member between 1 to 1000000!");exit; }
    if(avgOrd >=1 && avgOrd<=1000 && avgOrd != NaN) { }
    else {  alert("Average order size between 1 to 1000!");exit; }
    if(menRetainPM<=100 && menRetainPM != NaN) {

    } 
    else {  alert("% value between 1 to 100!");exit; }
    if(menRetainPM == '') {
        menRetainPM = 10;
    }


    $(".container2").show();
    var start = 1;
    var end = 100
}
function animateValue(id, start, end, duration) {
    var range = end - start;
    var current = start;
    var increment = end > start? 1 : -1;
    var stepTime = Math.abs(Math.floor(duration / range));
    var obj = document.getElementById(id);
    var timer = setInterval(function() {
        current += increment;
        obj.innerHTML = current;
        if (current == end) {
            clearInterval(timer);
        }
    }, stepTime);
}
animateValue("value", start, end, 2000);
</script>

现在,如果我发送ajax请求而不是admin-ajax.php(例如/ test.php),则数据会正常传递。

问题是,admin-ajax.php将始终返回0,因为它有以下几行:

var data = new FormData();
jQuery.each(jQuery('input[data-field=file]')[0].files, function(i, file) {
    data.append('file-'+i, file);
});

$.ajax({
    url : '/wp-admin/admin-ajax.php',
    data: data,
    cache: false,
    contentType: false,
    processData: false,
    method: 'POST',
    success: function(data){
        console.log(data);
    },
    error: function() {
        console.log("Error");
    }
});

e.preventDefault();

如果我尝试传递这样的数据(使用 processData:false ):

if ( empty( $_REQUEST['action'] ) )
    wp_die( '0', 400 );

admin-ajax.php仍然以0结束。

如果我删除 processData:false ,我会收到未捕获的TypeError:非法调用错误,我甚至无法将数据发送到管理员-ajax.php。

到目前为止,对我来说这似乎是一个问题。我错过了什么吗?

1 个答案:

答案 0 :(得分:1)

  

如果我尝试传递这样的数据(使用processData:false):

data: {
    action: 'cas_contact_form',
    data: data, }, admin-ajax.php still dies with a 0.

您现在通过在数据对象中引入另一个data键,将其余数据“降低一级”。但是接收端可能希望数据字段和操作键处于同一级别。

但是您可以像添加输入字段一样将此附加参数附加到FormData对象:

data.append('action', 'cas_contact_form');

https://developer.mozilla.org/en-US/docs/Web/API/FormData/append