【问题标题】:How to cancel the http request after 2 minutes in Javascript form submit?如何在 Javascript 表单提交 2 分钟后取消 http 请求?
【发布时间】:2017-08-31 03:47:50
【问题描述】:

Javascript表单提交中是否有2分钟后取消请求的属性

Javascript 代码

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();

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

$http({
        method : 'POST',
        **timeout : 120000,**

    }).success(function(data) {

    }).error(function(data, status) {

    });

【问题讨论】:

    标签: javascript forms http timeout form-submit


    【解决方案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,没有属性或方法可以在表单元素级别中止表单提交。

    【讨论】:

    • 谢谢你的回答,我今天试试这个
    • @Lakshman 你的问题解决了吗?如果是,也许你可以“接受”这个答案?
    【解决方案2】:

    这种方法的解决方案是从表单中删除 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
    
    }
    

    【讨论】:

    • 我想在表单提交中实现这个
    猜你喜欢
    • 1970-01-01
    • 2010-09-12
    • 1970-01-01
    • 1970-01-01
    • 2020-01-25
    • 1970-01-01
    • 2010-09-13
    • 2019-01-27
    • 1970-01-01
    相关资源
    最近更新 更多