保存表单输入到txt,弹出结果,不换页

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

我想在我的网站上建立一个时事通讯订阅功能。我想将所有输入保存到主机文件夹中的 txt 文件中。但是,我不想在人们提交后切换页面。只需显示一条弹出消息说 "Thank You for Subscribing" 就完美了。我知道如何使用 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();



});

看看source article