【问题标题】:internal server eroor 500 django when using simplejson.loads(request.raw_post_data)使用 simplejson.loads(request.raw_post_data) 时的内部服务器错误 500 django
【发布时间】:2013-05-08 14:03:21
【问题描述】:

我正在尝试从我的 jquery 客户端接收一个 json 对象,但是当我调用 simplejson.loads(request.raw_post_data) 时,我收到内部服务器错误 500。服务器收到调用,因为我收到了来自注释 simplejson.loads(request.raw_post_data) 行时的服务器。但是一旦我取消注释该行,就会引发错误。

ajaxtest.html

    <!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
            $("#post").click(function(){
            var test = new Object();
            test.name = "Kalle";
            test.pw = "kula";
            $.ajax({
                url: "ajaxtest/",
                type: 'POST',
                dataType: 'json',
                data: {client_response: JSON.stringify(test), csrfmiddlewaretoken: '{{  csrf_token}}'},
                success: function(result) {
                    alert(result);
                } 
            });
        });      
    });
</script>

views.py

from django.shortcuts import render
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponse
from django.utils import simplejson
from manges.models import User

# Create your views here.

def ajax_test(request):
print 'Hej'
if request.method == 'GET':
    print 'GET'
    c = User.objects.get(pk=1)
    print c.emailadress
    print c.password
    return HttpResponse(simplejson.dumps(c, default=User.serializable))
if request.method == 'POST':
    print 'POST'
    data = simplejson.load(request.raw_post_data)
    print json_data.name
    return HttpResponse(simplejson.dumps('Got JSON!'))      

def start_page(request):
print 'Start'
return render_to_response('ajaxtest.html',      context_instance=RequestContext(request))

urls.py

from django.conf.urls import patterns, include, url
from manges.views import ajax_test, start_page
from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns('manges.views',
url(r'^$', start_page),
url(r'^ajaxtest/$', ajax_test),
# Examples:
# url(r'^$', 'myforum.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),

url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),  
)

有什么想法吗??

【问题讨论】:

  • 请开启 DEBUG = True 并添加完整的错误堆栈跟踪

标签: jquery django json internal-server-error


【解决方案1】:

raw_post_data 不包含 JSON,这就是引发转换的原因。

当你发送请求时,你传递了这个数据

{client_response: JSON.stringify(test), csrfmiddlewaretoken: '{{  csrf_token}}'}

Jquery 在 POST 参数中序列化该对象。请参阅jQuery.ajax 的页面。

所以在服务器端,HttpRequest.raw_post_data 没有直接的 JSON。要提取 JSON,您需要使用包含 JSON 的 POST 参数,可通过

request.POST["client_response"]

【讨论】:

    猜你喜欢
    • 2015-06-25
    • 2015-03-05
    • 2015-02-12
    • 2018-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-23
    相关资源
    最近更新 更多