问题
I have a problem with the Slim Framework and a PUT request. I have a litte jQuery script that that will update an expiry time when a button is clicked.
$("#expiry-button").click(function(event) {
event.preventDefault();
$.ajax({
url: 'http://www.domain.com/expiry/38/',
dataType: 'json',
type: 'PUT',
contentType: 'application/json',
data: {aid:'38'},
success: function(){
var text = "Time updated";
$('#expiry').text(text).addClass("ok");
},
error: function(data) {
var text = "Something went wrong!";
$('#expiry').text(text).addClass("error");
}
});
});
I always get "Something went wrong!"
In my index.php where I have configured Slim, I have this
$app->put('/expiry/:aid/', function($aid) use($app, $adverts) {
$id = $app->request()->put($aid);
$adverts->expand_ad_time($id["aid"]);
});
if I var_dump($id)
I get NULL
the Response Header looks like this:
Status Code: 200
Pragma: no-cache
Date: Wed, 08 May 2013 12:04:16 GMT
Content-Encoding: gzip
Server: Apache/2.2.16 (Debian)
X-Powered-By: PHP/5.3.3-7+squeeze15
Vary: Accept-Encoding
Content-Type: text/html; charset=utf-8
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Transfer-Encoding: chunked
Connection: Keep-Alive
Keep-Alive: timeout=15, max=100
Expires: Thu, 19 Nov 1981 08:52:00 GMT
and the Request Body
Request Url: http://www.domain.com/expiry/38/
Request Method: PUT
Status Code: 200
Params: {
"aid": "38"
}
So the communication is there, but not the desired result. What am I doing wrong?
回答1:
First you should check that json data, because it isn't valid: http://jsonlint.com/ Try with this: {"aid":"38"}
If you need that JSON data than i would do something like this:
$app->put('/expiry/:aid/', function($aid) use($app, $adverts) {
// Decode the request data
$test = json_decode($app->getInstance()->request()->getBody());
echo $test->aid; // from the JSON DATA
});
If you want the number from the url /expiry/38/ then, you can get it from the variable $aid, which you've passed to the function
$app->put('/expiry/:aid/', function($aid) use($app, $adverts) {
echo $aid; // from the url
});
I hope this may help you
来源:https://stackoverflow.com/questions/16440344/slim-put-returns-null