2017-09-05 20 views
1

在模板中我发送数据使用XMLHttpResponse。如何让我的views.py中的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发送数据?

回答

0

你应该知道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 
} 
相关问题