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

标签 javascript php html popup response

我想为我的网站建立新闻通讯订阅功能。我想将所有输入保存到主机文件夹中的 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();



});

看看source article

关于javascript - 将表单输入保存到txt,弹出结果,不改变页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37017683/

相关文章:

javascript - 如何使用 Javascript 以与 PHP 相同的方式获取数据

javascript - 更新 angularjs 库会导致 angular.bootstrap() 出现错误

javascript - 仅在主页上加载的脚本出现在其他路由上

html - 输入字段 HTML 中来自 OTP SMS 的自动填充代码,例如在 Safari 中

javascript - 打印时如何在一张 A4 纸上放置两个 HTML div?

php - 在结账页面和 WooCommerce 数据字段中添加取货地点自定义字段

php - 使用 Codeigniter PHP 在我的管理面板中显示 Google Analytics 数据的最佳 API?

php - 从 BLOB 获取部分数据作为十六进制

html - 如何在 HTML 文本输入字段中隐藏插入符号?

c# - asp.net中的div截图