使用纯javascript实现创建表单并提交的方法

  •   
  • 4598
  • jQuery
  • 3
  • super_dodo
  • 2014/02/07

在一些应用中需要点击一个按钮或者链接实现删除或者影藏等更多的功能模块.且该模块需要实现表单的方式进行提交相关的信息验证到指定的方法.下面就是使用纯javascript进行的方法示例.可模仿改造后使用.

	
<ul class="actions">
	<li><a href="http://localhost/nodes/91/edit" rel="inspect">编辑</a></li>
	<li><a href="http://localhost/nodes/91/hide" onclick="javascript:hide();return false;">隐藏</a></li>
	<li><a href="http://localhost/nodes/91/del" onclick="javascript:del();return false;">删除</a></li>
	<li><a href="http://localhost/nodes/91/del" onclick="if(confirm('..')){...del的函数体};return false;">删除</a></li>
</ul>
<script type="text/javascript">	
//删除的函数方法--亦可压缩组合写在一行里面
function del(){
	if(confirm('Are you sure you wish to delete this node?')){
		var f = document.createElement('form'); 
		f.style.display = 'none'; 
		this.parentNode.appendChild(f); 
		f.method = 'POST'; 
		f.action = this.href;
		
		var m = document.createElement('input'); 
		m.setAttribute('type', 'hidden');
		m.setAttribute('name', '_method'); 
		m.setAttribute('value', 'delete'); 
		f.appendChild(m);
		
		var s = document.createElement('input'); 
		s.setAttribute('type', 'hidden'); 
		s.setAttribute('name', 'authenticity_token'); 
		s.setAttribute('value', 'lhzUtuxOsuZtuI44IVH'); 
		f.appendChild(s);
		f.submit(); 
	};
	return false;
}

//隐藏的函数方法
function hide(){
	var f = document.createElement('form');
	f.style.display = 'none';
	this.parentNode.appendChild(f);
	f.method = 'POST';
	f.action = this.href;
	
	var m = document.createElement('input');
	m.setAttribute('type', 'hidden');
	m.setAttribute('name', '_method');
	m.setAttribute('value', 'put');
	f.appendChild(m);
	
	var s = document.createElement('input');
	s.setAttribute('type', 'hidden');
	s.setAttribute('name', 'authenticity_token');
	s.setAttribute('value', 'lhzUtuxOsuZtuI44IVH');
	f.appendChild(s);
	f.submit();
	return false;
}
</script>

The heart wants what the heart wants. 心随所愿。