简体   繁体   English

如何使用XMLHttpRequest将参数从javascript传递到RESTful Web服务

[英]How can I pass a parameter from javascript to RESTful web service using XMLHttpRequest

When i try to print the received parameter at the web service. 当我尝试在Web服务上打印接收到的参数时。 The parameter is empty. 该参数为空。 If I view domain server log of glass fish server I can see the following print: 如果查看玻璃鱼服务器的域服务器日志,则可以看到以下打印:

Inside getJson() 内在getJson()
countryKey = countryKey =

So I understand the request arruved to the web service, but the parameter that was sent from the javascript url is empty 因此,我了解到请求已存储到Web服务,但是从javascript网址发送的参数为空

// This is the code of the web service method

@GET
@Produces(MediaType.APPLICATION_JSON)
public String getJson(String countryKey) {
    System.out.println("Inside getJson()");
    System.out.println("countryKey = " + countryKey);

    return "countryKey = " + countryKey;
}

// This is the javascript method
function populateDistrictList() {
    var element = document.getElementById("selectCountry");
    var selectedCountryKey = element.value;
    var selectedCountry = element.options[element.selectedIndex].text;
    var xmlHttp = new XMLHttpRequest();
    var url = "http://localhost:8080/MissionWS/webresources/generic?selectedCountryKey="+selectedCountryKey;
    xmlHttp.open('GET', url, true);
    xmlHttp.responseType = 'json';

    if (xmlHttp) {
        xmlHttp.onreadystatechange = function () {
            if (xmlHttp.readyState == 4) {
                if (xmlHttp.status == 200) {
                    alert(xmlHttp.responseText);
                } else {
                    alert("Something is wrong !");
                }
            }
        };
        xmlHttp.send();
    }
}

请尝试将@QueryParam添加到您的方法签名中,如下所示。

public String getJson(@QueryParam("selectedCountryKey") String countryKey)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM