我正在尝试使用 jQuery 的 ajax 将数据发布到我的超薄 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->get() ,如果我删除它,我会在尝试 POST 时得到一个 405 Method Not Allowed 。很明显我没有执行 POST,它实际上是在调用 GET。我需要知道该怎么做才能通过 jquery 发布。这一切都发生在同一个域本地主机上
这是帖子的网络活动:
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
谢谢你的帮助