在Django中没有来自Ajax的POST数据

时间:2014-08-20 09:28:18

标签: javascript python ajax django

我想在AJAX中将一组数据发布到Django-Site。 来自Javascript的代码:

var arr = {};
arr["first"] = "first";
arr["second"] = "second";
arr["third"] = "third";
var success = ""
    var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
     var rawtext = xmlhttp.responseText;

     document.getElementById("myDiv").innerHTML= jsonToHTMLTable(rawtext);
    }
  }
xmlhttp.open("POST","/AJAX?modus=create");  
xmlhttp.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
alert(JSON.stringify(arr));
xmlhttp.send({data:JSON.stringify(arr)});

但是当我调试(使用Eclipse)时,我没有看到数组或其他有用的字段。

这是来自django的代码:

def AJAX(request):
if request.method == 'POST':
    method = request.REQUEST.get("modus","")
    if method == 'create':
        test = request.POST['data']

更多信息 来自Django-Debug的回溯

Environment:
Request Method: POST
Request URL: http://localhost:8000/AJAX?modus=create
Django Version: 1.6.5
Python Version: 3.4.1
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
  112. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Lee\web\reportingTool\ReportingTool\TempDosage\views.py" in AJAX
14. test = request.POST['data']
File "C:\Python34\lib\site-packages\django\utils\datastructures.py" in __getitem__
301.             raise MultiValueDictKeyError(repr(key))
Exception Type: MultiValueDictKeyError at /AJAX
Exception Value: "'data'"

如何访问我的数据?

1 个答案:

答案 0 :(得分:1)

我发现这部分错了(Javascript):

这是新的JavascriptPart(适用于我):

var arr = {};
arr["first"] = "first";
arr["second"] = "second";
arr["third"] = "third";
var success = ""
$.ajax({
type: "POST",
url: "/AJAX?modus=create",
data: {"data": JSON.stringify(arr)},
success: success,
dataType: "application/json",
headers: {"X-CSRFToken": getCookie('csrftoken')}
});

这是django-part(观点):

def AJAX(request):
  if request.method == 'POST':
      method = request.REQUEST.get("modus","")
      if method == 'create':
          data = request.POST.get('data');