首页 > 解决方案 > 将结果显示为“未定义”,而不是文本字段中的预期输出

问题描述

我想根据输入字段中给出的值将值填充到 4 个文本字段中。当控制来自输入字段时,将调用函数 getcredentials() ,该函数又调用 python 代码。python 代码从 excel 工作表中检索 4 个必需的值,并将结果作为字典返回。我尝试通过以下方式从结果字典中设置这 4 个值。请纠正我。

脚本 :

<script>
      function getcredentials() {
        var x = document.index.AWSID.value;
         console.log(x)
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.index.APPUSERNAME.value  = this.responseText['AppUsername'];
      document.index.APPPASSWORD.value  = this.responseText['AppPassword'];
      document.index.RDPUSERNAME.value  = this.responseText['RdpUsername'];
      document.index.RDPPASSWORD.value  = this.responseText['RdpPassword'];
    }
  };
  xhttp.open('POST', 'getcredentials', true);
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    /*xhttp.send(x);*/
    xhttp.send("x="+encodeURIComponent(x));
       }
    </script>

蟒蛇代码:

def getCredentials(request):
AwsId = request.POST.get('x')
result = {'RdpUsername' : 'Opsadmin', 
          'RdpPassword' : '--C0nt@1ns^Ph3n%l@l@n1n3--', 
          'AppUsername' : 'Admin', 
          'AppPassword' : 'M@St3r..CRM'}
result['RdpPassword'] = result['RdpPassword'] + AwsId[-5:]
result['AppPassword'] = result['AppPassword'] + AwsId[0:3]
response = HttpResponse(result)
return response

标签: javascriptpythonhtmldjangoajax

解决方案


您应该使用JsonResponse(result)而不是HttpResponse. 就像是:

from django.http import JsonResponse

def getCredentials(request):
    AwsId = request.POST.get('x')
    result = ...
    response = JsonResponse(result)
    return response


推荐阅读