【发布时间】:2015-03-28 14:25:30
【问题描述】:
您好,我有一个简单的 jquery 代码,请求放入 cakephp
$("#putBtn").click(function(){
var id = $("#searchTxt").val();
$.ajax({
url: 'http://localhost/cakephp/recipes/'+id,
type: 'PUT',
async: false,
cache: false,
dataType:'json',
data:{
name:"777",
number:"777"
},
success: function(data) {
console.log(data);
},
error: function(textStatus, errorThrown) {
console.log("error");
}
});
});
问题是当运行这个命令并将它发送到 cakephp 它犯了这个错误
/cakephp/recipes/1.请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'null' 不允许访问。 jquery-2.1.0.js:8556 错误
在我的 cakephp 中,我只是按照本教程进行操作 //book.cakephp.org/2.0/en/development/rest.html
public function edit($id) {
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');
header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Type");
$this->viewClass = 'json';
if ($this->Recipe->save($this->data)) {
$message = 'Saved';
} else {
$message = 'Error';
}
$this->set(array(
'message' => $message,
'_serialize' => array('message')
));
}
我还用
添加了 router.phpRouter::resourceMap(array(
array('action' => 'index', 'method' => 'GET', 'id' => false),
array('action' => 'view', 'method' => 'GET', 'id' => true),
array('action' => 'add', 'method' => 'POST', 'id' => false),
array('action' => 'edit', 'method' => 'PUT', 'id' => true),
array('action' => 'delete', 'method' => 'DELETE', 'id' => true),
array('action' => 'update', 'method' => 'POST', 'id' => true)
));
Router::mapResources('recipes');
Router::parseExtensions();
我不知道为什么 cakephp 不接受我的 PUT 或 DELETE 命令请求。 有什么建议或意见吗? .或者我做错了什么。提前谢谢。
【问题讨论】:
-
您不能将 XHR 请求发送到页面 url 中存在的组合以外的其他
: 组合。我猜页面 url 的端口不是默认的 80 .. -
url: 'http://localhost/cakephp/recipes/'+id, -
如果url在不同的ip地址怎么办?
标签: javascript php jquery api cakephp