2017-05-03 83 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) –