Javascript Cakephp REST API-put和delete不工作?
大家好,我有一个简单的jquery代码,可以请求对cakephp进行putJavascript Cakephp REST API-put和delete不工作?,javascript,php,jquery,api,cakephp,Javascript,Php,Jquery,Api,Cakephp,大家好,我有一个简单的jquery代码,可以请求对cakephp进行put $("#putBtn").click(function(){ var id = $("#searchTxt").val(); $.ajax({ url: 'http://localhost/cakephp/recipes/'+id, type: 'PUT', async: false, cache: false, dataTy
$("#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”标头。因此,不允许访问源“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.php和
Router::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命令请求。
有什么建议吗。或者我做错了什么。thx。我在CakePHP版本2.5.4解析PUT调用时遇到了类似的问题 不优雅,但这确实有效 前端代码: 后端代码(app/Controller/projectscoontroller.php) 结果:
测试此代码时,请检查控制台。它只会将您最初发送的内容发回,但会保证您的后端代码(CakePHP)现在可以解析这些JSON PUT请求。您不能将XHR请求发送到页面url中存在的组合之外的其他:组合。我猜页面url的端口不是默认的80..
url:'http://localhost/cakephp/recipes/“+id,
如果url位于不同的ip地址,该怎么办?
$("#myButton").click(function() {
$.ajax({
type : 'PUT',
url : '/projects/foo',
dataType : 'json',
data : JSON.stringify({
'projectId' : 789,
'desc' : "cheese cake",
}),
success: function(return_data) {
alert("success");
console.log(JSON.stringify(return_data));
},
error: function(return_data) {
alert("error");
console.log(JSON.stringify(return_data));
});
});
public function foo() {
$this->autoRender = false;
if($this->request->is('PUT')) {
$in = $this->request->data;
reset($in);
$in = json_decode(key($in), true);
$project_id = $in['projectId'];
$desc = $in['desc'];
}
$response = array(
'project_id' => $project_id,
'desc' => $desc,
);
echo json_encode($response);
exit;
}