我正在尝试使用jQuery的ajax将数据发布到我的slim api。
这里是jQuery
$.ajax({type:'POST',url:'/api/insert',dataType:'json',data:{name:'matname',label:'Material Name'},
success:function(data){
console.log(data);
}
});
和苗条的index.php
<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
function json($obj) {
header('Content-Type','application/json');
return json_encode($obj);
}
$app = new \Slim\Slim();
$app->post('/insert', function () {
$request = Slim::getInstance()->request();
$inputs = json_decode($request->getBody());
echo json($inputs);
});
?>
index.php中还有一个$ app-&gt; get(),如果我删除了,那么在尝试POST时我得到405方法不允许。很明显,我没有执行POST,它实际上是在调用GET。我需要知道如何通过jquery进行POST。这一切都发生在同一个域localhost
上以下是该帖子的网络活动:
Request URL:http://localhost/api/insert
Request Method:POST
Status Code:405 Method Not Allowed
Request Headersview source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:96
Content-Type:application/json; charset=UTF-8
Cookie:PHPSESSID=bhj4oot5epdi2rqkn45m0oqgr0
Host:localhost
Origin:http://localhost
Referer:http://localhost/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11
X-Requested-With:XMLHttpRequest
Request Payload
{"fid":3,"table":"input","label":"Material Name","name":"matname","type":"text","mandatory":"Y"}
Response Headersview source
Cache-Control:private
Connection:Keep-Alive
Content-Length:4
Content-Type:text/html
Date:Wed, 12 Dec 2012 15:49:15 GMT
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive:timeout=5, max=100
Pragma:no-cache
Server:Apache/2.2.22 (Unix) DAV/2 PHP/5.3.15 with Suhosin-Patch mod_ssl/2.2.22 OpenSSL/0.9.8r
X-Powered-By:PHP/5.3.15
感谢您的帮助
答案 0 :(得分:1)
请求将转到/api/insert
你的苗条匹配/insert
应该是一样的。
另一件事是你在apache上安装了DAV模块 允许您打开和关闭接受的方法
检查您的apache配置(站点配置)是否允许使用POST方法。
答案 1 :(得分:0)
试试这个
$inputs = json_decode($request->getBody(),true);
答案 2 :(得分:0)
试试这个
在Slim帖子定义中包含一个尾部斜杠
$app->post('/insert/', function () {