2017-09-05 32 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 
} 
相關問題