1

我有这个:

处理程序.py

class ChatHandler(BaseHandler):
    model = ChatMsg
    allowed_methods = ('POST','GET')

    def create(self, request, text):
        message = ChatMsg(user = request.user, text = request.POST['text'])
        message.save()
        return message

模板.html

    ...
    <script type="text/javascript">
    $(function(){
        $('.chat-btn').click(function(){
            $.ajax({
                url: '/api/post/',
                type: 'POST',
                dataType: 'application/json',
                data: {text: $('.chat').val()}
            })
        })
    })
    </script>
    ...

api/urls.py

chat_handler = Resource(ChatHandler, authentication=HttpBasicAuthentication)
urlpatterns = patterns('',
    ....
    url(r'^chat/$', chat_handler, {'emitter_format': 'json'}),
)

为什么,但是 ChatHandler 中允许使用 POST 方法?GET 方法有效。是错误还是我的代码错误?

4

1 回答 1

1

即使您没有在问题中包含此代码,我还是在您在评论中给出的 github 中找到了它...

您正在映射到不允许 POST 请求的处理程序

urls.py::snip ::

post_handler = Resource(PostHandler, authentication=auth)
chat_handler = Resource(ChatHandler, authentication=auth)
urlpatterns = patterns('',
    url(r'^post/$', post_handler , { 'emitter_format': 'json' }),
    url(r'^chat/$', chat_handler, {'emitter_format': 'json'}),
)

处理程序.py

# url: '/api/post'
# This has no `create` method and you are not 
# allowing POST methods, so it will fail if you make a POST
# request to this url
class PostHandler(BaseHandler):
    class Meta:
        model = Post

    # refuses POST requests to '/api/post'
    allowed_methods = ('GET',)


    def read(self, request):
        ...

# ur;: '/api/chat'
# This handler does have both a POST and GET method allowed.
# But your javascript is not sending a request here at all.
class ChatHandler(BaseHandler):
    class Meta:
        model = ChatMsg
    allowed_methods = ('POST', 'GET')

    def create(self, request, text):
        ...

    def read(self, request):
        ...

您的 javascript 请求正在发送到'/api/post/',该请求正在路由到PostHandler. 我感觉您希望它会发送给聊天处理程序。这意味着您需要将 javascript 请求 url 更改为'/api/chat/',或将代码移动到您期望的处理程序。

此外,您在处理程序中设置了错误的模型。它不需要Meta嵌套类。它应该是:

class PostHandler(BaseHandler):
    model = Post

class ChatHandler(BaseHandler):
    model = ChatMsg
于 2012-09-19T14:49:46.593 回答