简体   繁体   English

添加HTML表单标签后,JavaScript会执行,但魔术消失了

[英]When added HTML Form tag JavaScript executes, but magically disappeared

I had a successful execution before adding the form tag. 添加表单标记之前,我执行成功。 But somehow the JavaScript is replaced. 但是以某种方式替换了JavaScript。 Is there a way to do without this form submission. 有没有一种方法可以不提交此表单。 I need to pass the data to PHP. 我需要将数据传递给PHP。 Thank You in Advance.. 先感谢您..

This is the html I tried 这是我尝试过的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>

And here is the JavaScript file. 这是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; 
}

The problem is probably because your submit button have type="submit" . 问题可能是因为您的提交按钮具有type="submit" Since you mentioned it was working before adding the form tag, i'm guessing that submity() is the function that sends the data to PHP, but now that you added a form tag, it will not be executed. 既然您提到添加表单标记之前它已经起作用,所以我猜想submity()是将数据发送到PHP的函数,但是现在您添加了表单标记,它将不会执行。 This is because a clicking a button with type="submit" inside a form tag not only sends the form data to the link in the action attribute, but also navigates to it. 这是因为单击表单标记中type="submit"的按钮不仅将表单数据发送到action属性中的链接,而且还会导航到该链接。

I'm fairly sure I understand the issue with your original code - that being the inability to prevent the default action occurring when using the button. 我相当确定我理解您的原始代码存在的问题-这是无法防止在使用按钮时发生默认操作的问题。 I modified the code a little and added the ajax function which would allow the sending of the form data without reloading the page. 我稍微修改了代码并添加了ajax函数,该函数将允许发送表单数据而无需重新加载页面。 Essentially the same code but rewritten to use external event listeners rather than inline event handler calls. 本质上是相同的代码,但是重写为使用外部事件侦听器,而不是内联事件处理程序调用。 Hope i helps. 希望我能帮上忙。

<?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{}
        fieldset{border: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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM