How do I copy the HTML and user input, then send it to the server in an HTTP request?

时间:2019-01-18 18:14:27

标签: javascript html

I am trying to copy the HTML along with the user's input, but I haven't had any luck. This is my code where I try to clone the form, then http it to the php file where it would be saved. I know it won't work because I need to append it.

JS:

<script type="text/javascript">
function submit_form()
{ 
    var xmlHttp = null;
    var formData = new FormData();
    var form = document.getElementById('form_div');
    var cln = form.cloneNode(true);
    var saveForm = '<html><body>' + cln + '</body></html>';
    formData.append("saveform", saveForm);
    var xmlHttp = new XMLHttpRequest()
    xmlHttp.open('POST', 'http.php?nocache='+crt_date, true);

    xmlHttp.send(formData);
    xmlHttp.onreadystatechange = function()
    {
        if (xmlHttp.readyState == 4)
        {         
            if (xmlHttp.status == 200)
            {
                var responsetext = xmlHttp.responseText;
                alert("Your request was sent, " + responsetext);
            }
            else
            {
                var err_str = "There was a problem retrieving the data +\n";
                err_str += "statusText = " + xmlHttp.statusText + "\n";
                err_str += "status = " + xmlHttp.status;
            }

        }
    } 
}
</script>

HTML:

<HTML>
    <HEAD>
        <meta http-equiv="X-UA-Compatible" content="IE=11">
    </HEAD>
    <BODY>
        <DIV id = "form_div">
            <FORM id = "form">
                <INPUT type = "text" value = "" id = "example" name = "example">
                <INPUT type="button" value="Submit" onclick="javascript:submit_form()">
            </FORM>
        </DIV>
    </BODY>
</HTML>

2 个答案:

答案 0 :(得分:3)

You can't concatenate a node with a string, you need to use the innerHTML property to get the HTML.

But the HTML of an input doesn't include changes to its value. If you want this change to be reflected, you need to copy the value property to the value attribute.

var cln = form.cloneNode(true);
cln.querySelector("#example").setAttribute("value", document.querySelector("#example").value);
var saveForm = '<html><body>' + cln.innerHTML + '</body></html>';

答案 1 :(得分:0)

正如我所见,这就是您要尝试的事情,

var xmlHttp = null;
var formData = new FormData();
var form = document.getElementById('form_div');
var cln = form.cloneNode(true);
var saveForm = '<html><body>' + cln.innerHTML + '</body></html>';
formData.append("saveform", saveForm);
var xmlHttp = new XMLHttpRequest()
console.log(saveForm);    

https://jsfiddle.net/VectorVortec/7ycbw0tg/7/

这是在克隆时是否填写表格的问题。如果是这样,则此代码有效。如果没有,则应使用所选答案。