我有一个表单,我希望在提交完成后将条目保存在服务器上的文本文件中。
我正在使用的jquery是:
$(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",
contentType: 'application/json; charset=utf-8',
data: {data: fields},
success: function(data) {
$('#output').html(data);
}
});
} else {
alert("Storage Failed. Try refreshing");
}
});
});
我正在使用的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['data'];
$json = json_decode($dataObject);
echo $json;
file_put_contents('your_data.txt', $json);
?>
您可以在此处查看表单的实时版本:http://hackingarticles.com/marketer/
问题是我的代码没有将任何数据发布到http://hackingarticles.com/marketer/your_data.txt
我一直试图解决这个问题很长时间,但这对我不起作用。
感谢任何帮助。
干杯
答案 0 :(得分:1)
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>
答案 1 :(得分:0)
尝试在ajax请求中设置contentType
属性,例如contentType: 'application/json; charset=utf-8'
。我已经遇到过这个问题(没有向服务器发送任何数据)并解决了我的问题