如果您的浏览器 javascript 禁用,您将如何向服务器发送REST的操作字?
下面是我将RESTful动词发送到服务器的简单测试。它紧紧依赖于ajax的type: 'GET', etc
。
jquery的,
$( document ).ready(function() {
$(".rest-get").click(function(){
$.ajax({
type: 'GET',
url: 'server.php',
dataType: "json", // data type of response
success: function(){
//
}
});
return false;
});
$(".rest-post").click(function(){
$.ajax({
type: 'POST',
url: 'server.php',
dataType: "json", // data type of response
success: function(){
//
}
});
return false;
});
$(".rest-put").click(function(){
$.ajax({
type: 'PUT',
url: 'server.php',
dataType: "json", // data type of response
success: function(){
//
}
});
return false;
});
$(".rest-delete").click(function(){
$.ajax({
type: 'DELETE',
url: 'server.php',
dataType: "json", // data type of response
success: function(){
//
}
});
return false;
});
});
HTML,
<ul>
<li><a href="#" class="rest-get">Get</a></li>
<li><a href="#" class="rest-post">Post</a></li>
<li><a href="#" class="rest-put">Put</a></li>
<li><a href="#" class="rest-delete">Delete</a></li>
</ul>
PHP中,
<?php echo $_SERVER['REQUEST_METHOD'];?> // you get PUT, DELETE, GET, or POST
我知道我们可以从html的表单发送POST,
<form method="POST">
...
</form>
但 PUT 和 DELETE 呢?如果没有办法从HTML表单发送它们,那么当javascript被浏览器杀掉时,你的web服务或API会失败吗?
答案 0 :(得分:2)
您可以使用POST
,但另外发送以下内容:
PUT
<input type="hidden" name="_method" value="PUT"/>
删除
<input type="hidden" name="_method" value="DELETE"/>
答案 1 :(得分:1)
遗憾的是没有标准方法可以使用<form>
标记。
来源:http://www.w3.org/TR/html401/interact/forms.html#h-17.13.1
答案 2 :(得分:1)
HTML表单仅支持GET和POST,原因是与缓存有关的各种原因,是否可以安全地重复失败的请求等(PUT和DELETE支持在HTML 5草案中,但由于这些原因而丢弃)。
可以通过在表单中使用隐藏字段来指定实际方法来解决这些问题,然后在服务器上查找该字段。
<form method="post">
<input type="hidden" name="actualMethod" value="PUT" />
</form>
在服务器上,您可以获得以下内容:
$formMethod = isset ($_POST ['actualMethod'])? $_POST ['actualMethod']: $_SERVER ['REQUEST_METHOD'];
switch ($formMethod) {
case "PUT":
// ...
当然使用这个技巧有很多限制,但它应该足够简单的情况。