我运行以下js:
$(".save_post").on("click", function() {
var saveId = $(".my_post_id").attr("data-id");
console.log(saveId);
$.ajax({
url: "save.php",
data: saveId,
dataType: 'json',
type: 'POST',
success: function(json_object) {
console.log(json_object);
$(".save_post").text("Data has been saved.");
},
error: function(json_object) {
console.log(json_object);
$(".save_post").text("Failed to save data !");
}
});
});
console.log(saveId);
给出了248
这就是我想保存的内容。
PHP页面
$post_data = $_POST['data'];
if (!empty($post_data)) {
$file = fopen('data_save.json', 'w+');
fwrite($file, json_encode($post_data));
fclose($file);
echo json_encode('success');
}
var_dump($post_data);
如果我去save.php,我会得到以下内容并在点击后显示按钮文字无法保存数据!
Null
答案 0 :(得分:1)
删除dataType: 'json',
答案 1 :(得分:0)
试试这个
$(".save_post").on("click", function() {
var saveId = $(".my_post_id").attr("data-id");
console.log(saveId);
$.ajax({
url: "save.php",
data: {saveId:saveId},
dataType: 'json',
type: 'POST',
success: function(json_object) {
console.log(json_object);
$(".save_post").text("Data has been saved.");
},
error: function(json_object) {
console.log(json_object);
$(".save_post").text("Failed to save data !");
}
});
});
数据应该像{data:data}