在网上搜了整一下午了,包括看 jQuery 的官方 API 说明文档,还是搞不清楚如何在 HTML 客户端,通过 jQuery 的 XMLHTTPRequest 来实现对 Zend Framework 2 REST 服务器的 PUT 和 DELETE 的请求……
自学能力太差,这么简单的问题越搞越糊涂,求高人指点迷津!!!
<html>
<head>
<script type="text/javascript" src="jquery-1.8.2.js"></script>
</head>
<p>Delete the Book with ISBN:</p>
<form id="form_delete" action="http://library/books" method="post">
<p>ISBN: <input id="input_isbn" type="text" name="id" /></p>
<input type="submit" value="Delete" />
</form>
<script type="text/javascript">
/// <reference path="jquery-1.8.2.js" />
$.ajax({
url: 'http://library/books',
type: 'delete'
});
</script>
</html>
ZF2 Controller 部分 class BooksController extends AbstractRestfulController {
public function delete($id) {
//$this->getBooksTable()->deleteRowByPrimaryKey($id);
return "You delete a book!";
}
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
多次测试后决定放弃使用 form 中的 method/_method 提交方式。感谢 @lanisle 最开始的提示:
新的方法将使用 JS/DOM 和 jQuery 通过 button 的 onclick 事件来实现 DELETE 的提交方式。
JS 代码下面的代码已经测试可行。
<script type="text/javascript"> /// <reference path="jquery-1.8.2.min.js" /> function bookDelete() { // 取得用户输入 ISBN 值 var isbnValue = document.getElementById("id").value; // AJAX 提交 DELETE 请求 $.ajax({ url: 'http://library/books/' + isbnValue, type: 'delete', success: function(data) { console.log(data); }, error: function(code, message, details) { console.log(message); console.log(code);、 console.log(details); } }); } </script>form 内容修改<!-- 去掉 action 和 method 属性,使用最原始的 form 功能 --> <form id="form_delete"> <p>ISBN: <input id="id" type="text" name="id"></p> <!-- 放弃 submit 方式,改用 button 并使用 onclick 事件调用 JS 函数 --> <input id="input_delete" type="button" value="Delete" onclick="bookDelete()" /> </form>是否支持PUT和DELETE请求取决于浏览器,jquery文档也有标注:
一般情况下是需要POST请求配合隐藏域来支持PUT和DELETE的,对于jquery而言,直接附带一个"_method"参数就好了。
Good luck!