记录关于实现restful的例子:
1.列举 index.html
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://"+document.getElementById('ip').value+"/test.php/hello/get",true);
xmlhttp.send();
setTimeout('loadXMLDoc()',1000);
}
function restfullset()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv2").innerHTML=xmlhttp.responseText;
// document.getElementById("myDiv").innerHTML=xmlhttp.responseXML.xml;
}
}
var url= "http://"+document.getElementById('ip').value+"/test.php/hello/put/"+document.getElementById('testset').value;
xmlhttp.open("PUT",url,true);
xmlhttp.send();
}
</script>
</head>
<body>
input remote ip:<input type="text" id="ip" value="172.21.73.167">
<h2>test for restful GET</h2>
<div id="myDiv">show</div>
<button type="button" οnclick="loadXMLDoc()">get</button>
<h2>test for restful PUT</h2>
<input type="text" id="testset">
<button type="button" οnclick="restfullset()">put</button>
<div id="myDiv2"></div>
</body>
</html>
2.列举 test.php
<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
// GET route
$app->get(
'/hello/get',
function () {
$i=rand(1,100);
if ($i >"50") {
$s="on";
}else{
$s="off";
}
echo "CO2 is:$i<br>";
echo "fun is: $s";
}
);
// PUT route
$app->put(
'/hello/put/:str',
function ($str) use ($app){
exec("echo $str >> /tmp/webset");
echo "remote server recieved:\"$str\" ,and it have been writen to /tmp/webset!!";
}
);
// DELETE route
$app->delete(
'/hello/delete',
function () {
echo 'This is a DELETE route';
}
);
$app->run();
关于silm的文档参见官方手册:http://docs.slimframework.com/