Http请求状态
问题描述:
我需要向服务器提交数据(使用带有表单的帖子)并捕获返回状态,以便我可以返回解析或拒绝。我无法使用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>
感谢
答
这不能用JavaScript来完成。表单提交会向服务器创建一个新请求,因此您将被引导至另一个页面,而不是您所在的另一个页面,在这种情况下,它将返回响应,如同'server.php'
一样,然后返回响应服务器。它取决于你下一步从'server.php'
为了跟踪服务器的状态,你可以从'server.php'
返回到请求页面,并在返回的URL中使用查询字符串或将你的数据添加到服务器会话并在返回页面时捕获它们。
'我不能使用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 - 这是特别不是“允许”用于您的问题 –