防止从DOM表单提交刷新

时间:2017-08-07 13:32:23

标签: javascript angularjs forms dom

我想知道是否可以通过以下代码阻止页面在提交时刷新:

var new_element         = document.createElement('input');
new_element.type        = 'hidden';
new_element.name        = 'save';
new_element.value       = '';

var form_element = document.getElementById('document_form');    

form_element.appendChild(new_element);

form_element.submit();  

1 个答案:

答案 0 :(得分:0)

表单提交操作是导航事件,如果您不想重新加载页面,则必须不使用提交操作。 然后你需要生成另一种策略,例如使用ajax发送请求并获得响应。

这是一个jquery示例:

$.post( "ajax/test.html", function( data ) {
  //data contains the response
});

或使用你在评论中写的AngularJS:

$http({
  method: 'POST',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

此处有关agularjs $ http对象https://docs.angularjs.org/api/ng/service/$http

的详细信息
相关问题