2017-04-02 126 views
1

我有一个问题,无论我做什么使用JQuery和Ajax提交表单,但它仍然将我重定向到表单的操作页面,我不明白,如果外面的事情影响功能或发生什么。 这是我的代码:用ajax提交表单而不重新加载页面?

<form action="add-niveau" method="POST" class="ajax"> 
    <div> 
    <input type="text" name="name" placeholder="Your name"> 
    </div> 
    <div> 
    <input type="text" name="email" placeholder="Your email"> 
    </div> 
    <div> 
    <textarea rows="4" cols="20" name="comment"></textarea> 
    </div> 
    <input type="submit" value="send"> 
</form> 
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js">  </script> 
<script> 
    $('form.ajax').on('submit', function() { 
    return false; 
    }); 
</script> 

其他Ajax脚本:

var ajaxRequest; 

function ajaxFunction() { 
try { 

    // Opera 8.0+, Firefox, Safari 
    ajaxRequest = new XMLHttpRequest(); 
} catch (e) { 

    // Internet Explorer Browsers 
    try { 
     ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); 
    } catch (e) { 

     try { 
      ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); 
     } catch (e) { 

      // Something went wrong 
      alert("Your browser broke!"); 
      return false; 
     } 
    } 
} 
} 

function getForm(objButton) { 
ajaxFunction(); 
ajaxRequest.onreadystatechange = function() { 
    if (ajaxRequest.readyState == 4) { 
     document.getElementById("formTag").innerHTML = ajaxRequest.responseText; 
    } 
} 
var buttonValue = objButton.value; 
ajaxRequest.open("get", "get-form/" + buttonValue, true); 
ajaxRequest.send(null); 
} 

// Send form using ajax: 
$('form.ajax').on('submit', function(e) { 
    e.preventDefault(); 
}); 
+0

将事件传递给您的函数并使用'event.preventDefault'。 – Roljhon

+1

打开控制台,检查错误。确保你包含jquery。 –

+0

你可以发布你使用ajax的代码 – Akashii

回答

0

您需要添加event.preventDefault();因为你想阻止默认的表单提交,因此在点击事件之后。

$('form.ajax').on('submit', function(event) { // pass the event to function 

    event.preventDefault(); // add this line 

    $.ajax({ 
     url: "test.php", 
     context: document.body 
    }).done(function() { 
     alert('Done!'); 
    }); 

}); 
+0

我使用ajax将表单上传到我的网站的问题,在这一点上,我得到了上述问题,但是当我在其他页面单独测试窗体和函数时,它工作正常,所以还有其他影响功能! –

相关问题