我正在使用YiiBackboneBoilerplate。我想用这样的数据填充模型:
- 模型 -
define([
'jquery',
'underscore',
'backbone'
], function($, _, Backbone) {
var EvaluateModel = Backbone.Model.extend({
urlRoot: 'evaluate/process',
defaults: {
title: '',
state: 1
}
});
return EvaluateModel;
});
- 在我看来 -
initialize:function() {
var result = new Evaluate({id:this.id});
result.fetch({
success: function(result, response) {
JSON.stringify(result.model);
}
});
},
- Yii行动 -
public function actionProcess() {
//I have tryed this
echo json_encode('test');
Yii::app()->end();
//and this
$this->sendResponse(200, CJSON::encode(array('title' => 'test')));
}
我正在获取textStatus:parsererror,从服务器返回的结果包含当前页面的html
此外,fetch()应该根据app.js中的初始设置发送POST请求类型,但类型是 GET
- app.js -
// initialize Http object to make backbone work with POST instead of GET
Http.initialize({type:'POST'});
可能出现什么问题?
答案 0 :(得分:0)
我没有看到任何引用Http.initialize
的文档。那是从哪里来的?由于您从服务器获取现有模型,因此即使模拟HTTP(http://backbonejs.org/#Sync-emulateHTTP),Backbone也会默认发出GET请求。
其次,可能发生的一件事是服务器端框架忽略了application/json
请求内容类型类型,并且只会在您调用mypage.json
URL时返回JSON(即它正在考虑只有扩展名。)
默认情况下,Backbond将使用内容类型/api/cars/12
获取(例如)application/json
以获取与汽车模型实例qith id 12相关的数据。因为它在内容类型中请求了JSON,所以期望返回JSON。如果您改为调用(例如)/api/cars/12.json
,某些Web框架默认只返回其API返回JSON数据。或者,也许您的API无法返回JSON(即API不会自动执行,并且您自己没有配置它。)
答案 1 :(得分:0)
我正在从服务器发送json数据,如下所示:
protected function sendResponse($status = 200, $body = '', $contentType = 'application/json')
{
// Set the status
$statusHeader = 'HTTP/1.1 ' . $status . ' ' . $this->getStatusCodeMessage($status);
header($statusHeader);
// Set the content type
header('Content-type: ' . $contentType);
echo $body;
Yii::app()->end();
}
protected function getStatusCodeMessage($status)
{
$codes = array(
100 => 'Continue',
101 => 'Switching Protocols',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
306 => '(Unused)',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
);
return (isset($codes[$status])) ? $codes[$status] : '';
}