2017-05-03 85 views
0

我做了一個REST服務,如果登錄爲真,它將返回一個字符串「hej」。 我用Java測試了一個休息客戶端,它工作正常,但對JavaScript來說很新,需要一些幫助。使用Javascript和REST登錄

我使用這個功能

function UserAction() { 
console.log(User()); 
var xhttp = new XMLHttpRequest(); 
xhttp.open("GET", "http://localhost:8080/Footballmanagerrestservice/webresources/login"); 
    xhttp.setRequestHeader("login", User()); 
    xhttp.responseType = 'text'; 

xhttp.onreadystatechange = function() { 
    console.log('DONE', xhttp.readyState); 
    if (xhttp.readyState == 4) {; 
     // handle response 
     var response = xhttp.responseText; 
     console.log(response); 
     if (response == "hej") { 
      var url = "http://localhost:8080/FM3/spil2.jsp"; 
      window.location.href = url; 
     } 
    } 
}; 

// send the request *after* the callback is defined 
xhttp.send(); 
return false; 
} 

function User() { 
username = document.getElementById("username").toString(); 
username = document.getElementById("password").toString(); 
var UserAndPass = "?username=" + username + "&password=" + password; 
return UserAndPass; 
} 

我告訴你的客戶,我有我的Java,也許你可以看到爲什麼它不工作。

public static void main(String[] args) { 
    Client client = ClientBuilder.newClient(); 

    String root="http://localhost:8080/Footballmanagerrestservice/webresources/"; 


String functionPath="login"; 

String parameters="?username=s153518&password=holger"; 
Response res = client.target(root+functionPath+parameters) 
     .request(MediaType.APPLICATION_JSON).get(); 
String svar = res.readEntity(String.class); 
System.out.println(svar); 
} 
+0

您指定的Java的用戶名​​和密碼,但在javascript登錄。什麼是用戶()? – AhmadWabbi

+0

@AhmadWabbi添加用戶功能:-) –

回答

1

代碼的第一部分看起來不錯,下面,而不是必須在函數內部處理,因爲在本質上是異步

var response = JSON.parse(xhttp.responseText); 
console.log(response); 
if (response.toString() == "hej") { 
    var url = "http://localhost:8080/FM3/spil2.jsp"; 
    window.location.href = url 
} 
return false; 

DOC:https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/onreadystatechange

基本上你想處理響應作爲同步調用,但它不是,響應不立即可用,因此,您必須註冊一個回調(從文檔必須附加到字段onreadystatechange),該回調將由javascript觸發爲服務器響應即可使用。

試圖改變它,像這樣:

xhttp.onreadystatechange = function() { 
    if (xhttp.readyState == 4) { 
     // handle response 
     var response = JSON.parse(xhttp.responseText); 
     console.log(response); 
     if (response.toString() == "hej") { 
     var url = "http://localhost:8080/FM3/spil2.jsp"; 
     window.location.href = url 
     } 
    } 
    } 

    xhr.send(); 
+0

我仍然處於學習狀態,對於JavaScript和REST很新穎。你能否更深入地解釋你的意思? –

+0

好吧,我會修復我的答案:) – Karim

+0

好吧,我試着改變代碼,我得到2錯誤。 GET http:// localhost:8080/Footballmanagerrestservice/webresources/404(Not Found) 你有任何想法爲什麼找不到它? Java客戶端工作正常。 而接下來誤差 未捕獲的語法錯誤:意外標記<在JSON在位置0 在JSON.parse() 在XMLHttpRequest.UserAction.xhttp.onreadystatechange(load_user.js:18) 在UserAction(load_user.js: 28) at HTMLFormElement.onsubmit(index_1_1.html:51) –