如何在Safari中ajax成功后提交表单

时间:2016-09-18 17:29:19

标签: javascript ajax safari form-submit

我有一个带有提交按钮的表单。我把onclick =" foo(事件,这个);"在提交的提交按钮中。

我想在ajax成功之后提交表单。

这是我的代码:

<form id="form_a" action="destination.html">

  <input type="submit" id="submit_button_1" value="Submit button 1" onclick="foo(event, this);">

</form> 

<script type="text/javascript">

function foo(event, this_element)
{
    event = event || window.event;
    event_target = event.target || event.srcElement;

    //Prevent the immediate submission because I want submit after ajax success : 
    event.preventDefault();

    //Retrieve the submit button clicked :
    if(this_element.id == "submit_button_1")
    {   
            //Submit the form afer ajax success :

            var xhr = new XMLHttpRequest();

            xhr.onreadystatechange = function()
            {
                if(xhr.readyState == 4 && xhr.status == 200)
                {
                    //Retrieve the form object to submit :
                    form_a = document.getElementById("form_a");

                    //Submit the form 3000 ms later : 
                    setTimeout('form_a.submit();', 3000);
                }    
            } 

            //Send ajax request on server :
            xhr.open("POST", "server.php", false);
            xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xhr.send("");
    }
}

</script>

此代码在safari中不起作用。那么如何在safari成功之后提交表格?

1 个答案:

答案 0 :(得分:0)

您正在尝试执行字符串。变量form_在执行时可能不可用。

您的setTimeout应该是这样的,以便通过closure访问form_a变量。

setTimeout(function() {
   form_a.submit();
}, 3000);