通过AJAX发送从localStorage的数据到PHP,并将其保存在一个HTML文件 [英] Send data from localStorage via AJAX to PHP and save it in an HTML file

查看:951
本文介绍了通过AJAX发送从localStorage的数据到PHP,并将其保存在一个HTML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个表单发送字段中的数据通过AJAX的文件,我发现这个解决方案在线:<一href="http://techglimpse.com/pass-localstorage-data-php-ajax-jquery/">http://techglimpse.com/pass-localstorage-data-php-ajax-jquery/

I want to send fields data from a form to a file via AJAX and I found this solution online: http://techglimpse.com/pass-localstorage-data-php-ajax-jquery/

唯一的问题是,我有多个字段,而不是一个单一的领域,我想保存的输出(localStorage的)在HTML(或任何其他格式)文件,而不是显示它在#output股利。

The only problem is that I have multiple fields instead of a single field and I want to save the output (localStorage) in an HTML (or any other format) file instead of showing it in an #output div.

我怎么能这样做?

您可以看到我的工作,我已经做了到现在位置:保存使用AJAX到PHP 表单数据

You can see my work that I've done till now here: Save form data using AJAX to PHP

和这里是我的HTML / JS code: http://jsbin.com/iSorEYu/1/edit&安培; PHP code http://jsbin.com/OGIbEDuX/1/edit

And here's my HTML/JS code: http://jsbin.com/iSorEYu/1/edit & PHP code 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);
?>

记者:

<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>

注意:替换your_data文件的文件格式在PHP code到HTML,如果你想在HTML格式的JSON数据的

NOTE: Replace the file format of your_data file to html in the PHP code if you want your JSON data in HTML format.

这篇关于通过AJAX发送从localStorage的数据到PHP,并将其保存在一个HTML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆