我需要向服務器提交數據(使用帶有表單的帖子)並捕獲返回狀態,以便我可以返回解析或拒絕。我無法使用ajax來發出XMLHttpRequest請求。我想知道如何提交表單並返回一個承諾(如'承諾構造函數'上的@SomeKittens answer)。 custom.js:Http請求狀態
var myfunction =
{
submitForm: function()
{
// Create form
var form = document.createElement('form');
form.setAttribute('action', 'server.php');
form.setAttribute('method', 'POST');
var input1 = document.createElement('input');
input1.setAttribute('type', 'hidden');
input1.setAttribute('name', 'params');
input1.setAttribute('id', 'params');
input1.setAttribute('value', 'myvalue');
form.appendChild(input1);
// Create iframe and append form to it
var $frame = $('<iframe style="width:500px;height:400px;display:none;">');
$('body').html($frame);
setTimeout(function(){
var doc = $frame[0].contentWindow.document;
var $body = $('body',doc);
$body.html(form);
// submit form
$(form).submit();}, 1);
}
}
的index.html:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="custom.js"></script>
</head>
<body>
<script>
myfunction.submitForm().done(function() {
alert('It works');
}).fail(function() {
alert('Failed');});
</script>
</body>
</html>
感謝
'我不能使用ajax來提出請求既不XMLHttpRequest.' - 首先,如果你不能使用Ajax,那麼你當然不能使用xhr,因爲xhr是一個以ajax開頭的方法!如果你不能使用ajax,那麼你基本上只剩下使用標準表單提交機制......這導致新的頁面被加載......所以,承諾完全不可能太 –
@Jaromanda,I知道它(我在那個答案中看到:http://stackoverflow.com/questions/8039402/where-is-jquery-ajax-defined-in-the-jquery-source-code)。我必須使用返回數據(服務器將返回數據)的承諾,並根據狀態顯示'它的工作'或'它失敗' – dramans
不知道該問題中的任何答案將如何幫助您不使用「AJAX或XHR」 - 因爲這個問題和答案都是關於jQuery.ajax的...這是使用XMLHttpRequest的AJAX - 這是特別不是「允許」用於您的問題 –