jQuery向CherryPy的DELETE请求未发送参数
有个问题,当我用 jQuery (1.4.4) 向 CherryPy 服务器 (3.1.2) 发出 DELETE 请求时,参数没有被发送出去。而 POST、GET 和 PUT 请求的参数都能正常发送。
这是 CherryPy 服务器的代码:
import cherrypy
class DeleteExample(object):
exposed = True
def PUT(self, *args, **kwargs):
print kwargs
def DELETE(self, *args, **kwargs):
print kwargs
global_conf = {'global': {'server.socket_port': 8080},
'/': {'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
'tools.staticdir.root': '/home/kevin/workspace/delete_example',
'tools.staticdir.on': True,
'tools.staticdir.dir': 'src',
'tools.staticdir.index': 'index.html'}
}
cherrypy.quickstart(DeleteExample(), config=global_conf)
这是包含 jQuery 代码的 index.html:
<html>
<head>
<script type="text/javascript" src="jquery-1.4.4.js"></script>
<script>
$(document).ready(function() {
$.ajax({
type: "PUT",
url: "http://localhost:8080",
dataType: "json",
data: {first: 10, second: 200}
});
$.ajax({
type: "DELETE",
url: "http://localhost:8080",
dataType: "json",
data: {first: 10, second: 200}
});
});
</script>
</head>
<body>
</body>
</html>
这是从 CherryPy 网络服务器打印出来的内容:
{'second': '200', 'first': '10'}
127.0.0.1 - - [23/Jan/2011:04:02:48] "PUT / HTTP/1.1" 200 19 "http://localhost:8080/" "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.13) Gecko/20101206 Ubuntu/10.04 (lucid) Firefox/3.6.13"
{}
127.0.0.1 - - [23/Jan/2011:04:02:51] "DELETE / HTTP/1.1" 200 19 "http://localhost:8080/" "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.13) Gecko/20101206 Ubuntu/10.04 (lucid) Firefox/3.6.13"
你可以看到,用 .ajax 函数发出的 PUT 和 DELETE 请求几乎一模一样,唯一的区别就是请求类型。但是,奇怪的是,PUT 请求能发送所有参数,而 DELETE 请求却一个参数都没发送。
有没有人知道为什么 DELETE 请求没有发送正确的参数呢?
2 个回答
0
我遇到了一个非常类似的问题,我必须在请求的主体中发送一些内容。变量 kwargs
也是空的,我找到了这个解决办法:
cherrypy.request.body.readline()
它返回了
b'somekey=2cefe65093df'
你可以这样做
import urllib.parse
...
urllib.parse.parse_qs(cherrypy.request.body.readline().decode("utf-8"))
它返回了
{'somekey': ['2cefe65093df']}
3
看起来你想发送一个带有请求内容的DELETE请求,这种做法是... 不太常见。 (GET请求也是一样的道理)。