2017-08-24 53 views
1

我正在尝试POST ajax调用我的后端。 这是工作的罚款,如果我设置async: false,但如果我删除它失败和错误部分只有Ajax-POST成功异步是假

$.ajax({ 
     type: "POST", 
     enctype: 'multipart/form-data', 
     url: "http://localhost:8000/student/queue/create", 
     data: data, 
     processData: false, 
     contentType: false, 
     cache: false, 
     timeout: 600000, 
     success: function (data) { 
      console.log("SUCCESS : ", data); 

     }, 
     error: function (e) { 
      console.log("ERROR : ", e.responseText); 
      alert("ERROR : "+ e.responseText); 

     } 
    }); 

返回undefined从按钮调用我的AJAX功能的onclick

<button type="submit" id="submit-createqueue" class="btn feedback glass" onclick="sendformDataToBackend()">Submit</button> 

我想Ajax Call returns undefined when async is true但也无法正常工作

function Call(data) { 

    return $.ajax({ 
     url: "http://localhost:8000/student/queue/create", 
     type: "POST", 
     enctype: 'multipart/form-data', 
     data: data, 
     processData: false, 
     contentType: false, 
     cache: false, 
     timeout: 600000, 

     error: function (e) { 
     console.log("ERROR : ", e.responseText); 
     alert("ERROR : "+ e.responseText); 
     } 

    }); 
} 

Call(data).then(function(data) { 
    console.log(data); 
    alert("test") 
}); 
+1

你需要停止表单提交这也是发生当您单击提交按钮。它与'async:false'一起工作,因为它在请求正在处理时阻塞处理 - 这正是你不应该使用它的原因。我也强烈建议你停止使用'on *'事件属性。使用不显眼的事件处理程序 –

+0

谢谢,我提交窗体标记外,现在它正在工作异步也 –

+0

很高兴你得到它的工作,但这不是一个真正可行的解决方案,因为它打破了无障碍功能。我为你添加了一个答案,它提供了一个更好的方法 - 通过钩住你的'

'元素的'submit'事件 –

回答

1

您需要停止单击提交按钮时也发生的表单提交。它与async: false一起工作,因为它在请求正在处理的同时阻止处理 - 这正是你不应该使用它的原因。

我也强烈建议您停止使用on*事件属性。请使用不显眼的事件处理程序。

当你使用jQuery,可以实现既使用此代码的那些:

$('#yourFormElement').on('submit', function(e) { 
    e.preventDefault(); 

    var data = // your logic to get form data here... 

    $.ajax({ 
    type: "POST", 
    enctype: 'multipart/form-data', 
    url: "http://localhost:8000/student/queue/create", 
    data: data, 
    processData: false, 
    contentType: false, 
    cache: false, 
    timeout: 600000, 
    success: function (data) { 
     console.log("SUCCESS : ", data); 
    }, 
    error: function (e) { 
     console.log("ERROR : ", e.responseText); 
     alert("ERROR : " + e.responseText); 
    } 
    }); 
}); 
0

请将输入类型按钮替换为提交按钮

+0

这不是一个真正可行的解决方案,因为它会影响辅助功能标准。 –