2017-08-24 92 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

這不是一個真正可行的解決方案,因爲它會影響輔助功能標準。 –