Bha*_*wla 9 php forms ajax jquery local-storage
我想通过AJAX将字段数据从表单发送到文件,我在网上找到了这个解决方案:http://techglimpse.com/pass-localstorage-data-php-ajax-jquery/
唯一的问题是我有多个字段而不是单个字段,我想将输出(localStorage)保存在HTML(或任何其他格式)文件中,而不是在#output div中显示它.
我怎样才能做到这一点?
你可以看到我迄今为止所完成的工作:使用AJAX将表格数据保存到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);
?>
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
注意:如果您想要HTML格式的JSON数据,请将your_data文件的文件格式替换为PHP代码中的html.
你是在过度整合事物.对localStorage的检查可以更简单(其他选项).jQuery有一个serialze()函数,它接受所有表单元素并将其序列化.您可以将它们存储在"eloqua-fields"下,以便您可以再次找到它.不需要做一些花哨的随机反击.
我想补充一点,并非所有代码都有意义.如果在每次DOM准备就绪时清除它,为什么要使用localstorage?如果有错误,您的验证不会中止发送过程,但我认为您只是想玩一些东西.
$(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").val(""); //this ONLY clears input fields, you also need to reset other fields like select boxes,...
alert("Now Passing stored data to Server through AJAX jQuery");
$.ajax({
type: "POST",
url: "backend.php",
data: {data: fields},
success: function(data) {
$('#output').html(data);
}
});
} else {
alert("Storage Failed. Try refreshing");
}
});
});
Run Code Online (Sandbox Code Playgroud)
对于服务器部分,如果您只想将数据存储在某个地方.
$dataObject = $_POST['data'];
$json = json_decode($dataObject);
file_put_contents('your_data.txt', $json) ;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14779 次 |
| 最近记录: |