【发布时间】:2017-05-14 14:37:51
【问题描述】:
我需要向服务器提交数据(使用带有表单的帖子)并捕获返回状态,以便我可以返回解决或拒绝。我不能使用 ajax 来发出请求,也不是 XMLHttpRequest。我想知道如何提交表单并返回一个承诺(如@SomeKittens answer '承诺构造函数')。 自定义.js:
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>
谢谢
【问题讨论】:
-
I cannot use ajax to make the request neither XMLHttpRequest.- 首先,如果你不能使用 AjAX,那么你当然不能使用 xhr,因为 xhr 是 ajax 开始的方式!!如果你不能使用 ajax,那么你基本上只能使用标准的表单提交机制......这会导致一个新页面被加载......所以,Promises 也是完全不可能的 -
@Jaromanda,我知道(我在那个答案中看到:stackoverflow.com/questions/8039402/…)。我必须对返回数据使用承诺(服务器将返回数据)并根据状态显示“它工作”或“它失败”
-
不确定该问题中的任何答案将如何帮助您不使用“AJAX 或 XHR” - 因为该问题和答案都是关于 jQuery.ajax ......这是使用 XMLHttpRequest 的 AJAX - 它明确不允许在您的问题中使用
标签: javascript php jquery http