簡體   English   中英

在Django中使用javascript進行ajax調用

[英]ajax call with javascript in django

<input type="text" onkeyup="checkPin();" id="pin"/>

大家好,我是django的新手,我試圖通過視圖def pincheck():訪問數據庫def pincheck():我正在通過javascript進行嘗試,但是發生了一些錯誤。

function checkPin(){
    var pin_code=document.getElementById("pin").value;
    if(pin_code.length == 6){        
        if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
        }
        else{// code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function(){
            if (xmlhttp.readyState==4 && xmlhttp.status==200){
                document.getElementById("innerHTML").innerHTML=xmlhttp.responseText;
            }
            else if (request.status === 404) {  
                alert("Oh no, it does not exist!");
            }  
            else if (request.status === 403) {  
                alert("Oh no, it does not exist!");
            }  
        }
      var data = "{% csrf_token %}";
      xmlhttp.setRequestHeader('X-CSRF-Token', data);
      xmlhttp.open("POST", "../../sellerprofile/ajaxcall/");
      xmlhttp.send();
    }
}

這是我的JavaScript,如果有錯,請糾正我。 錯誤是Uncaught InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.

代碼的問題是,您設置標題時沒有實際打開連接,這就是為什么它提供InvalidStateError的原因。 正確的方法是先打開連接,然后設置標題。 以下是修改后的代碼。

function checkPin(){
var pin_code=document.getElementById("pin").value;
if(pin_code.length == 6){        
    if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else{// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            document.getElementById("innerHTML").innerHTML=xmlhttp.responseText;
        }
        else if (request.status === 404) {  
            alert("Oh no, it does not exist!");
        }  
        else if (request.status === 403) {  
            alert("Oh no, it does not exist!");
        }  
    }
  var data = "{% csrf_token %}";
  xmlhttp.open("POST", "../../sellerprofile/ajaxcall/");
  xmlhttp.setRequestHeader('X-CSRF-Token', data);
  xmlhttp.send();
}

}

我希望它會起作用;)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM