【问题标题】:How to get the XMLHttpResponse send data in my views.py?如何在我的views.py 中获取XMLHttpResponse 发送数据?
【发布时间】:2018-02-13 06:29:03
【问题描述】:

在我发送数据的模板中使用 XMLHttpResponse。

我的代码如下:

...
<input type="button" value="ajax1" onclick="ajax1()">


<script>

    function ajax1(){
        var xhr = new XMLHttpRequest();
        xhr.open('GET', '/ajax1/', true);  
        xhr.send("name=root;pwd=123");  // send data
    }

</script>

但是我怎样才能在views.py接收数据呢?

在我的views.py

def ajax1(request):
    print request.GET.get('name'), request.GET.get('pwd') # all is None.
    return HttpResponse('ajax1')

你看,我用request.GET.get(param_key)获取数据失败。

如何在我的views.py中获取XMLHttpResponse发送数据?

【问题讨论】:

    标签: python django xmlhttprequest


    【解决方案1】:

    你应该知道 XMLHttpResponse 的send() 方法是发送请求体。 您的请求方法是 GET。所以你不能传递数据。

    你尝试使用 post 方法来传递这样的数据:

    function ajax1(){
        var xhr = getXHR();
    
        xhr.onreadystatechange = function(){  
            if (xhr.readyState == 4) {   
    
                console.log(xhr.responseText); 
    
                var json_obj = JSON.parse(xhr.responseText);
                console.log(json_obj);
    
            }
        }; 
    
        xhr.open("POST", "/ajax1/", true);   
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset-UTF-8"); // add the request header
    
        xhr.send("name=root; pwd=123;");  // send data
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-08
      • 2017-04-21
      • 1970-01-01
      • 2012-11-23
      • 1970-01-01
      • 2021-09-26
      • 2018-04-22
      相关资源
      最近更新 更多