douzhuo2722
2018-03-28 10:10
浏览 40

将数据从js保存到php失败

I run the following 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); gives 248 which is what I would like to save.

PHP page

$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);

I get if I go to save.php i get the following and the button text after I click says Failed to save data !

Null

图片转代码服务由CSDN问答提供 功能建议

我运行以下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(“数据已保存。”); 
},
错误:function(json_object){
 console.log(json_object); 
 $(“  .save_post“)。text(”无法保存数据!“); 
} 
}); 
}); 
   
 
 

console .log(saveId); 给出 248 这就是我要保存的内容。

PHP页面 < pre> $ 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

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • donglian1982 2018-03-28 10:17
    已采纳

    Made it work by removing dataType: 'json',

    已采纳该答案
    打赏 评论
  • duanba7653 2018-03-28 10:17

    Try this

    $(".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 should be passed in ajax like {data:data}

    打赏 评论

相关推荐 更多相似问题