0
변수를 AJAX에 전달할 때 변수 값을 일부만 입력하면 작동합니다. var userid = "test"
및 var passwd = "test1"
인데 변수가 var userid = form.userid.value
및 var passwd = form.passwrd.value
인 경우에는 그렇지 않습니다. form.userid.value
및 form.passwrd.value
이 작동하지 않는 이유는 무엇입니까? 여기 AJAX 호출에 Javascript 변수를 전달하면 작동하지 않습니다.
<html>
<head>
<title>
Login page
</title>
<script src="login.js"></script>
<!-- jQuery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<!-- jQuery -->
<script src="./jquery.rest.min.js"></script>
<script src="./webtoolkit.base64.js"></script>
</head>
<body>
<h1 style="font-family:Comic Sans Ms;text-align="center";font-size:20pt;
color:#00FF00;>
Simple Login Page
</h1>
<form name="login">
Username<input type="text" name="userid"/>
Password<input type="password" name="pswrd"/>
<input type="button" onclick="checkLogin(this.form)" value="Login"/>
<input type="reset" value="Cancel"/>
</form>
</body>
</html>
이 작동하지 않는 자바 스크립트 (
login.js
)입니다 :
function checkLogin(form) {
var auth_token = localStorage.getItem("token");
//the variables which do not correctly pass through to AJAX call
var userid = form.userid.value;
var passwd = form.pswrd.value;
if(auth_token == null) {
$.ajax({
type: 'POST',
data: {
username: userid,
password: passwd
},
url: 'http://127.0.0.1:8000/api/v1/api-token-auth/',
success: function(res){
var tok = res.token
localStorage.setItem("token", JSON.stringify(tok));
}});
} else {
$.ajax({
type: 'POST',
headers: {
'Authorization':'token ' + JSON.parse(auth_token)
},
data: {
quote_text: "Test Javascript with variable token pt 2",
tags: '["test", "javascript"]'
},
url: 'http://127.0.0.1:8000/api/v1/test/',
success: function(res){
console.log(res) //answer of api call.
}
});
};
};
그러나이 작동합니다 나는 하드 사용자 이름과 암호를 코딩 한 (login.js
여기
function checkLogin(form) {
var auth_token = localStorage.getItem("token");
//hard coded variable content which works.
var userid = "test";
var passwd = "test1";
if(auth_token == null) {
$.ajax({
type: 'POST',
data: {
username: userid,
password: passwd
},
url: 'http://127.0.0.1:8000/api/v1/api-token-auth/',
success: function(res){
var tok = res.token
localStorage.setItem("token", JSON.stringify(tok));
}});
} else {
$.ajax({
type: 'POST',
headers: {
'Authorization':'token ' + JSON.parse(auth_token)
},
data: {
quote_text: "Test Javascript with variable token pt 2",
tags: '["test", "javascript"]'
},
url: 'http://127.0.0.1:8000/api/v1/test/',
success: function(res){
console.log(res) //answer of api call.
}
});
};
};
"작동하지 않는"것은 무엇입니까? 요청 전에 변수 값을 console.log()로 시도하십시오. 어쩌면'form.userid.value'와'form.pswrd.value'가 null이거나 정의되지 않았을 수도 있습니다. 또한 Google 크롬 개발자 도구의 네트워크 탭에서 요청의 실제로드 된 내용을 확인할 수 있습니다. – molerat
Blah. 두 시간 동안 시도한 후 브라우저를 닫은 후 다시 열면 작동합니다. 죄송합니다. – shaz