我一直试图了解Backbone如何工作并与后端代码进行通信,我遇到了无法接收发送到我的php文件的JSON的问题。
这是代码: HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link href='http://fonts.googleapis.com/css?family=Abel' rel='stylesheet' type='text/css' />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Understanding Backbone</title>
<style type="text/css">
body { padding: 0; margin: 0; background-color: #fff; }
h2 { font-family: Abel, sans-serif; margin: 0; padding: 0 0 5px 0;}
input { background-color: #ddd; border: 0; }
input:active { background-color: #bbb; }
#new-status { margin: 20px; padding: 20px; background-color: #67A9C3; }
#statuses { margin: 20px; padding: 20px; background-color: #92B456; }
</style>
</head>
<body>
<div id="new-status">
<h2>New monolog</h2>
<form>
<textarea id="status" name="status"></textarea>
<br />
<input type="submit" value="Post" />
</form>
</div>
<div id="statuses">
<h2>Monologs</h2>
<ul></ul>
</div>
<script src="js/jquery-min.js"></script>
<script src="js/underscore.js"></script>
<script src="js/backbone.js"></script>
<script src="js/main.js"></script>
</body>
</html>
JS:
var Status = Backbone.Model.extend({
url: 'api/index.php'
});
var Statuses = Backbone.Collection.extend({
model: Status
});
var NewStatusView = Backbone.View.extend({
events: {
"submit form": "addStatus"
},
initialize: function(options) {
this.collection.on("add", this.clearInput, this);
},
addStatus: function(e) {
e.preventDefault();
this.collection.create({ text: this.$('textarea').val() });
},
clearInput: function() {
this.$('textarea').val('');
}
});
var StatusesView = Backbone.View.extend({
initialize: function(options) {
this.collection.on("add", this.appendStatus, this);
},
appendStatus: function(status) {
this.$('ul').append('<li>' + status.escape("text") + '</li>');
}
});
$(document).ready(function() {
var statuses = new Statuses();
new NewStatusView({ el: $('#new-status'), collection: statuses });
new StatusesView({ el: $('#statuses'), collection: statuses });
});
的index.php:
<?php
echo(var_dump($_POST));
?>
这是我得到的答案:
array(0){ }
我一直在打破这个,所以请帮助!
答案 0 :(得分:3)
经过对stackoverflow(真棒社区顺便说一句)的更多研究之后,我发现骨干不会发送直接帖子或者发送到RESTful api,或者代码隐藏可能是什么,而是它是一组头文件。所以你必须围绕$ _SERVER全局并找出所请求的内容。您将能够在$ _SERVER [“REQUEST_METHOD”]中找到您的请求,而不是执行一个开关/案例来决定您要对该请求做什么。通过(在骨干的情况下总是一个JSON字符串)发送的数据在HTTP正文中并且为了解决它我使用了file_get_contents('php:// input'),并解码了JSON以便php可以使用它
<?php
$requestMethod = $_SERVER["REQUEST_METHOD"];
switch ($requestMethod)
{
case 'POST': $data = json_decode(file_get_contents('php://input'), true);
echo $data;
break;
}
?>
@orangewarp,我真的很想了解在没有使用RESTful php框架的情况下发生的事情。
答案 1 :(得分:0)
$raw_data = file_get_contents("php://input");
var_dump($raw_data);
if( !empty($raw_data) ){
$data = @json_decode($raw_data, true);
if( $data ){
var_dump($data);
}
}