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

时间:2017-05-27 07:19:23

标签: javascript rest netbeans parameter-passing

当我尝试在Web服务上打印接收的参数时。 参数为空。 如果我查看玻璃鱼服务器的域服务器日志,我可以看到以下内容 印刷:

  

在getJson()里面   countryKey =

所以我理解了Web服务的请求,但参数 从javascript url发送的是空的

// 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();
    }
}

1 个答案:

答案 0 :(得分:0)

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

public String getJson(@QueryParam("selectedCountryKey") String countryKey)
相关问题