ajax call not performed in firefox when form submits

时间:2015-07-14 19:33:28

标签: javascript jquery ajax firefox

I don't know what I'm doing wrong. The following snippet works fine in Chrome but not in Firefox. The odd thing is, if I test in Firefox and add a breakpoint, e.g. at "request.send(params)" and do a "Step Over" everything works fine. But if I perform a "Continue" it also wont work.

Does anybody know, what I'm doing wrong? Thanks

    $(document).ready(function(){
    var form =$("form#my_form"); 
    var id = form.id;
   form.submit(function(event){ 
      event.preventDefault();      
    myVar.myMethod(document.getElementById('my_input_1').value, document.getElementById('my_input_2').value);

     this.submit();
   });
});


var myVar = {};

myVar.myMethod = function(par1, par2) {
    params = "par1=" + par1 + "&par2=" + par2;
    request = new XMLHttpRequest();
    request.open("POST", "Destination", true);
    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    request.setRequestHeader("Content-length", params.length);
    request.setRequestHeader("Connection", "close");
    request.send(params);
};

2 个答案:

答案 0 :(得分:0)

我不确定为什么它在Chrome中运行 - 可能只是速度之类。

听起来像你的ajax请求(异步)没有在this.submit()之前发送;您需要在myVar.myMethod中编写某种回调,只有在XHR完成后才会处理。

更好的方法可能是(因为你使用的是jQuery,但没有真正使用它):

$(document).ready(function(){
    var form =$("form#my_form"); 
    var id = form.id;
    form.submit(function(event){ 
        event.preventDefault();
        $.post({
            url: '??', // from form - the url you submitted to
            data: {par1: $('#my_input_1').val(), par2: $('#my_input_2').val() }
            success: function( data ) {
                //handle the returned data
            }
        })
    });
});

或者,如果您尝试将POST数据中的这两个字段提交到表单的url属性,则只需在下一页上获取POST数据时处理POST数据 - 换句话说,只要输入他们应该以POST的形式发送到网址。

答案 1 :(得分:0)

我删除了this.submit() - Line,现在一切正常。感谢David Votrubec和charlietfl的评论,这些评论让我走上了正轨。

        $(document).ready(function(){
    var form =$("form#my_form"); 
    var id = form.id;
   form.submit(function(event){ 
      event.preventDefault();      
    myVar.myMethod(document.getElementById('my_input_1').value, document.getElementById('my_input_2').value);
   });
});


var myVar = {};

myVar.myMethod = function(par1, par2) {
    params = "par1=" + par1 + "&par2=" + par2;
    request = new XMLHttpRequest();
    request.open("POST", "Destination", true);
    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    request.setRequestHeader("Content-length", params.length);
    request.setRequestHeader("Connection", "close");
    request.send(params);
};