将表单输入保存到txt,弹出结果,不更改页面


Save form inputs to txt, popup result, no page changing

我想为我的网站建立一个时事通讯订阅功能。我想把所有输入保存到主机文件夹中的txt文件中。然而,我不想在人们提交后切换页面。只需显示一条弹出消息,说"谢谢你的订阅"就完美了。我知道如何使用PHP在单独的页面中显示消息,但不知道如何在弹出框中显示。这是我的html和PHP代码。请帮忙,非常感谢。

<html>
<head>
    <title></title>
</head>
<body>
    <form>
        <form action="myprocessingscript.php" method="post">
        <input name="field1" type="text" />
        <input name="field2" type="text" />
        <input type="submit" name="submit" value="Save Data">
    </form>
    <a href='data.txt'>Text file</a>
</body>

PHP函数是

<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
    $data = $_POST['field1'] . '-' . $_POST['field2'] . "'n";
    $ret = file_put_contents('/tmp/mydata.txt', $data, FILE_APPEND | LOCK_EX);
    if($ret === false) {
        die('There was an error writing this file');
    }
    else {
        echo "$ret bytes written to file";
    }
}
else {
   die('no post data to process');
}

一旦您将jQuery包含到页面中,以下内容应该会起作用:

// process the form
$('form').submit(function(event) {
    // get the form data
    // there are many ways to get this data using jQuery (you can use the class or id also)
    var formData = {
        'field1'              : $('input[name=field1]').val(),
        'field2'             : $('input[name=field2]').val()
    };
    // process the form
    $.ajax({
        type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
        url         : 'myprocessingscript.php', // the url where we want to POST
        data        : formData, // our data object
        dataType    : 'json', // what type of data do we expect back from the server
                    encode          : true
    })
        // using the done promise callback
        .done(function(data) {
            // log data to the console so we can see
            console.log(data); 
            // data is the output from your php, check it and display alert appropriately
            // here we will handle errors and validation messages
        });
    // stop the form from submitting the normal way and refreshing the page
    event.preventDefault();

});

看看源文章