添加 HTML 表单标签时,JavaScript 执行,但神奇地消失了
Posted
技术标签:
【中文标题】添加 HTML 表单标签时,JavaScript 执行,但神奇地消失了【英文标题】:When added HTML Form tag JavaScript executes, but magically disappeared 【发布时间】:2019-07-06 05:44:18 【问题描述】:在添加表单标签之前我已经成功执行了。但不知何故,javascript 被替换了。有没有办法不用这个表单提交。我需要将数据传递给 php。提前谢谢你..
这是我试过的html
<!DOCTYPE html>
<html>
<head>
<script src="riu003.js"></script>
</head>
<body>
<form name="myform" method="post" action="/riu/riu-01/riu001.php" enctype="multipart/form-data">
<div id="aaa">
</div>
<button style="width: 100%" class="bbb" onclick="addfielderbutt()">Add Fields</button>
<button style="width: 100%; height: 45px; background-color: dodgerblue" onclick="submity()" type="Submit" value="submit">SUBMIT</button>
</form>
</body>
</html>
这是 JavaScript 文件。
function createElemented(element, attribute, inner)
if (typeof(element) === "undefined") return false;
if (typeof(inner) === "undefined") inner = "";
var el = document.createElement(element);
if (typeof(attribute) === 'object')
for (var key in attribute)
el.setAttribute(key, attribute[key]);
if (!Array.isArray(inner)) inner = [inner];
for (var k = 0; k < inner.length; k++)
if (inner[k].tagName)
el.appendChild(inner[k]);
else
el.appendChild(document.createTextNode(inner[k]));
return el;
;
var noofclicks = 0;
function addfielderbutt()
noofclicks = noofclicks + 1;
var uptexty = createElemented("TEXTAREA", class: "upt_" + noofclicks, name: "positiveuse_" + noofclicks, type: "text" , "Type the postive uses here...");
var nptexty = createElemented("TEXTAREA", class: "unt_" + noofclicks, name: "negativeuse_" + noofclicks, type: "text" , "Type the negative uses here...");
var dptexty = createElemented("TEXTAREA", class: "dpt_" + noofclicks, name: "positivedisuse_" + noofclicks, type: "text" , "Type the postive disuses here...");
var dntexty = createElemented("TEXTAREA", class: "dnt_" + noofclicks, name: "negativedisuse_" + noofclicks, type: "text" , "Type the negative disuses here...");
var breakkk = createElemented("BR");
document.getElementById("aaa").appendChild(uptexty);
document.getElementById("aaa").appendChild(nptexty);
document.getElementById("aaa").appendChild(dptexty);
document.getElementById("aaa").appendChild(dntexty);
document.getElementById("aaa").appendChild(breakkk);
function submity()
document.cookie = "numberofclicks="+noofclicks;
【问题讨论】:
请正确格式化您的源代码,并为您的submity()
函数添加源代码。我相信这可能是问题所在。此外,如果您想在不重定向/移动客户端的情况下将数据提交到服务器,您可以使用ajax
,我建议您进行研究,因为这可能对您有用。
【参考方案1】:
问题可能是因为您的提交按钮有type="submit"
。由于您在添加表单标记之前提到它正在工作,我猜测submity()
是将数据发送到 PHP 的函数,但是现在您添加了表单标记,它将不会被执行。这是因为单击表单标记内带有type="submit"
的按钮不仅将表单数据发送到操作属性中的链接,而且还导航到该链接。
【讨论】:
我尝试了输入标签,但单击“添加字段”按钮时它仍然没有给出任何响应。【参考方案2】:我很确定我理解您的原始代码的问题 - 即无法阻止使用按钮时发生的默认操作。我稍微修改了代码并添加了 ajax 函数,该函数允许在不重新加载页面的情况下发送表单数据。本质上相同的代码,但重写为使用外部事件侦听器而不是内联事件处理程序调用。希望我能帮上忙。
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' )
/*
this is to emulate whatever code you have in
the form action /riu/riu-01/riu001.php
*/
exit( json_encode( $_POST ) );
?>
<!DOCTYPE html>
<html>
<head>
<title>You have got to have a title...</title>
<style>
button width: 100%;height:45px;background-color: dodgerblue
.bbb
fieldsetborder:none;
</style>
<script>
document.addEventListener('DOMContentLoaded',()=>
/*
presumably this will be in riu003.js
------------------------------------
*/
let counter = 0; // the counter to be incremented.
let url=location.href; // change this to "/riu/riu-01/riu001.php"
const submity=function(e)
/*
explicitly prevent the default form submission
*/
e.preventDefault();
/* The payload is a FormData object */
let payload=new FormData( document.querySelector('form[name="myform"]') );
/*
The callback can do far more than this...
*/
let callback=function( r )
alert( r )
/*
send the ajax request to the backend PHP script.
The actual url used will not be `location.href`
according to the original code...
*/
ajax.call( this, url, payload, callback );
;
/* a variation on the createElemented function */
const create=function(type,attributes,parent)
try
let el = ( typeof( type )=='undefined' || type==null ) ? document.createElement( 'div' ) : document.createElement( type );
let _arr=['innerhtml','innertext','html','text'];
for( let x in attributes ) if( attributes.hasOwnProperty( x ) && !~_arr.indexOf( x ) ) el.setAttribute( x, attributes[ x ] );
if( attributes.hasOwnProperty('innerHTML') || attributes.hasOwnProperty('html') ) el.innerHTML=attributes.innerHTML || attributes.html;
if( attributes.hasOwnProperty('innerText') || attributes.hasOwnProperty('text') ) el.innerText=attributes.innerText || attributes.text;
if( parent!=null ) typeof( parent )=='object' ? parent.appendChild( el ) : document.getElementById( parent ).appendChild( el );
return el;
catch( err )
console.warn( err.message );
;
/* ultra basic ajax function to send a POST request */
const ajax=function(url,payload,callback)
let xhr=new XMLHttpRequest();
xhr.onreadystatechange=function()
if( this.status==200 && this.readyState==4 )callback.call( this, this.response );
xhr.open('POST',url,true);
xhr.send(payload);
;
const addfielderbutt=function(e)
counter++;
/* explicitly prevent the default action being triggered */
e.preventDefault();
/* create a fieldset and append new children to it */
let fieldset=create( 'fieldset', , document.getElementById('aaa') );
/* add the children */
create( 'textarea', 'class':'upt_' + counter, name:'positiveuse_' + counter ,fieldset );
create( 'textarea', 'class':'unt_' + counter, name:'negativeuse_' + counter ,fieldset );
create( 'textarea', 'class':'dpt_' + counter, name:'positivedisuse_' + counter ,fieldset );
create( 'textarea', 'class':'dnt_' + counter, name:'negativedisuse_' + counter ,fieldset );
;
/*
Bind the event handlers to the buttons
*/
document.querySelector( 'button.bbb' ).addEventListener( 'click', addfielderbutt );
document.querySelector( 'button[ type="submit" ]' ).addEventListener( 'click', submity );
);
</script>
</head>
<body>
<form name='myform' method='post'>
<div id='aaa'>
<!-- generated content will appear here -->
</div>
<button class='bbb'>Add Fields</button>
<button type='Submit' value='submit'>SUBMIT</button>
</form>
</body>
</html>
【讨论】:
其实我不想用Ajax。不使用 Ajax 就不能做到这一点。我只想让文本框显示出来,但不知何故,我猜它在没有任何客户端响应的情况下被提交。你能解释一下为什么会发生这种情况。我真的需要 Ajax 来显示文本框吗? 当然可以。 ajax 只发送信息——它可以使用标准的提交方法。我只是不确定,因为为提交按钮分配了事件处理程序 - 似乎是多余的,除非submity
做了一些我们不知道的花哨的东西以上是关于添加 HTML 表单标签时,JavaScript 执行,但神奇地消失了的主要内容,如果未能解决你的问题,请参考以下文章
javascript Pardot表单 - 删除标签和添加占位符