加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

将数据从localStorage通过AJAX发送到PHP并将其保存在HTML文件中

发布时间:2020-12-16 01:34:58 所属栏目:百科 来源:网络整理
导读:我想通过 AJAX将表单数据从表单发送到文件,我在线发现了这个解决方案: http://techglimpse.com/pass-localstorage-data-php-ajax-jquery/ 唯一的问题是我有多个字段而不是单个字段,我想将输出(localStorage)保存在HTML(或任何其他格式)文件中,而不是在#outp
我想通过 AJAX将表单数据从表单发送到文件,我在线发现了这个解决方案: http://techglimpse.com/pass-localstorage-data-php-ajax-jquery/

唯一的问题是我有多个字段而不是单个字段,我想将输出(localStorage)保存在HTML(或任何其他格式)文件中,而不是在#output div中显示.

我怎样才能做到这一点?

你可以看到我迄今为止所做的工作:Save form data using AJAX to PHP

这是我的HTML / JS代码:http://jsbin.com/iSorEYu/1/edit& PHP代码http://jsbin.com/OGIbEDuX/1/edit

PHP:
<h1>Below is the data retrieved from SERVER</h1>
<?php
    date_default_timezone_set('America/Chicago'); // CDT
    echo '<h2>Server Timezone : ' . date_default_timezone_get() . '</h2>';
    $current_date = date('d/m/Y == H:i:s ');
    print "<h2>Server Time : " . $current_date . "</h2>";

    $dataObject = $_POST; //Fetching all posts

    echo "<pre>"; //making the dump look nice in html.
    var_dump($dataObject);
    echo "</pre>";

        //Writes it as json to the file,you can transform it any way you want
    $json = json_encode($dataObject);
    file_put_contents('your_data.txt',$json);
?>

JS:

<script type="text/javascript">
$(document).ready(function(){
localStorage.clear();

$("form").on("submit",function() {
    if(window.localStorage!==undefined) {
        var fields = $(this).serialize();

        localStorage.setItem("eloqua-fields",JSON.stringify( fields ));
        alert("Stored Succesfully");
        $(this).find("input[type=text]").val("");
        alert("Now Passing stored data to Server through AJAX jQuery");
        $.ajax({
           type: "POST",url: "backend.php",data: fields,success: function(data) {
              $('#output').html(data);
           }
        });
    } else {
        alert("Storage Failed. Try refreshing");
    }
});
});
</script>

注意:如果您希望使用HTML格式的JSON数据,请将your_data文件的文件格式替换为PHP代码中的HTML.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读