【问题标题】:showing results as 'Undefined', instead of expected output in text field将结果显示为“未定义”,而不是文本字段中的预期输出
【发布时间】:2021-04-08 04:23:41
【问题描述】:

我想根据输入字段中给出的值将值填充到 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>

python 代码:

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

【问题讨论】:

  • 您好,您是从后端返回普通字符串还是 json?另外,输入alert(this.responseText) 看看打印的内容。
  • 嗨斯瓦蒂,我在“结果”字典中有输出,并将结果传递给 HttpResponse 并返回响应。 alert(this.responseText) 正在将结果的键打印为字符串。

标签: javascript python html django ajax


【解决方案1】:

您应该使用JsonResponse(result) 而不是HttpResponse。比如:

from django.http import JsonResponse

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-26
    • 2014-09-19
    相关资源
    最近更新 更多