duanli6618 2012-12-24 23:27
浏览 32
已采纳

使用骨干.save方法尝试在php文件中提取json数据

I'm using backbone in my application and I'm attempting to update a json file using the backbone method .save method here is the site http://dalydd.com/projects/backbone/backbone.html

here is my js this is working fine

 var ModalInfo = Backbone.Model.extend({
defaults: {
  person:'',
  occupation:'',
  home:'',
},
url:'sample.php',
});

 var developer = new ModalInfo();
developer.toJSON();
 developer.save({person:'madan', occupation:'developer', home:'middtown'}, {
wait:true,
success:function(model, response) {
console.log('Successfully saved!' + model + response);
},
 error: function(model, error) {
console.log(model.toJSON());
console.log('error.responseText' +model);
}
});

Here is the php in my sample.php I'm trying to get the contents of json.js decode it append it with my new data and then decode it and return it as the response

 <?php

 $json_data = json_decode(file_get_contents('json.js'), true);
 for ($i = 0, $len = count($json_data); $i < $len; ++$i) {
      //do the right logic
 }
 file_put_contents('json.js', json_encode($json_data));
 $final_data = file_get_contents('json.js', json_encode($json_data));
 echo $final_data;
 echo(var_dump($_POST));
 ?>

when i try to echo out the super global post I get array(0)

I'm hoping someone could help me out with my php and why I can't extract any post data in sample.php when i use the .save method in backbone - when i echo out server request method it states post i just want to grab the post data and write it to the file and then return it am I going about this the wrong way - any help is appreciated - I have been racking my brain on this. My first step is just figuring out why i can't get any post data even though firebug is telling me it's posting when I load the page - you can check also

  • 写回答

1条回答 默认 最新

  • dongyi8795 2012-12-24 23:32
    关注

    The answer to your question lies in that fact that unless you are posting form-encoded data, the $_POST superglobal does not get populated by PHP. You need to get at the raw posted input. You can do that like this:

    $json_data = json_decode(file_get_contents('php://input'));
    

    You can actually use any of the various PHP file input methods here (i.e fopen/fread, file (useless in this context), etc.) . However the above will probably be the easiest if you are not going to be dealing with large chunks of JSON input to the point where memory management becomes more of a concern.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?