如何在Javascript表单提交2分钟后取消http请求?

时间:2017-04-05 13:31:07

标签: javascript forms http timeout form-submit

在Javascript表单提交2分钟后是否有任何属性要取消请求

Javascript代码

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MainCtrl">
    <h2>Watching Type Change</h2>
    Enter Type: <input ng-model="newType" /><br/>
    Using Type (with siblings): <span>Before</span><input dynamic-input="{{newType}}" watch="true" /><span>After</span><Br>
    Using Type (without siblings): <div><input dynamic-input="{{newType}}" watch="true" /></div>
    
    <br/><br/><br/>
    <h2>Without Watch</h3>
    Checkbox: <input dynamic-input="checkbox" /><br />
    Password: <input dynamic-input="{{ 'password' }}" value="password"/><br />
    Radio: <input dynamic-input="radio"  /><br/>
    Range: <input dynamic-input="{{ rangeType }}" />
</div>

类似于http配置对象中的超时。

var document = $document[0];
var form = document.createElement('form');
form.setAttribute('method', 'POST');
form.setAttribute('action', '/service/'+url);
var hiddenField = document.createElement('input');
hiddenField.setAttribute('type', 'hidden');
hiddenField.setAttribute('name', 'filterParam');
hiddenField.setAttribute('value',angular.toJson(input));
form.appendChild(hiddenField);
document.body.appendChild(form);
form.submit();

2 个答案:

答案 0 :(得分:1)

您可以使用window.stop(在IE中,它是document.execCommand("Stop"))来中止所有待处理的表单提交。代码是:

var document = $document[0];
var form = document.createElement('form');
form.setAttribute('method', 'POST');
form.setAttribute('action', '/service/'+url);
var hiddenField = document.createElement('input');
hiddenField.setAttribute('type', 'hidden');
hiddenField.setAttribute('name', 'filterParam');
hiddenField.setAttribute('value',angular.toJson(input));
form.appendChild(hiddenField);
document.body.appendChild(form);
form.submit();

setTimeout(function() {
    try {
        window.stop();
    } catch (exception) {
        document.execCommand('Stop');
    }
}, 120000);

根据表单元素的DOM interface,没有用于在表单元素级别上中止表单提交的属性或方法。

答案 1 :(得分:0)

此方法的解决方案可能是从表单中删除action属性并在javascript方法中触发ajax调用,您可以在其中手动处理超时。

类似的东西:

<form>
 ..
 <button ng-click="submit()" />
</form>

$scope.submit = function(){

    var promise= $q.defer();
    $http.get('/actionUrl', {timeout: promise.promise})
    .then(function(resp){

    })

    promise.resolve();  //cancel the request. you can set a timeout here

}