如何从客户端javascript运行服务器端功能?

时间:2016-12-30 15:26:30

标签: javascript java

debug.html

<head>
<script src="debugBoot.js"></script>
</head>
<body onload="init()">

<button onclick="alert(dss.getParameters())">Get Params</button>

</body>

debugBoot.js

var dss = {};

var INVALID_PARAM = -1;

function init() {

dss.getParameters = function(){
    var rest=new XMLHttpRequest();
    rest.open("GET", "http://localhost:8080/MW-war/rest/mw/enumerateParams", false);
    var data=rest.responseText;
    var jsonResponse = JSON.parse(data);   //line 11
    console.log(jsonResponse["Data"]);
    rest.send(jsonResponse);
    return JSON.parse(data);
};

}

MWRest(界面)

@GET
@Path("/enumerateParams")
@Produces(MediaType.APPLICATION_JSON)
public String[][] enumerateParams();

myJavaClass

    @Override
    public String[][] enumerateParams() {
    // TODO Auto-generated method stub

    return new String[][] { { "" + PATIENT_ID, "PATIENT_ID" }, { "" + AGE, "AGE" },
            { "" + BLOOD_PRESSURE, "BLOOD_PRESSURE" }, { "" + GENDER, "GENDER" },
            { "" + SMOKING_HABITS, "SMOKING_HABITS" }, { "" + DIET_FRUITS_VEGGIES, "DIET_FRUITS_VEGGIES" },
            { "" + CHOLESTEROL, "CHOLESTEROL" }, { "" + ALCOHOL, "ALCOHOL" }, { "" + ACTIVITY, "ACTIVITY" },
            { "" + QUIT_SMOKING, "QUIT_SMOKING" }, { "" + DIET_CEREAL_FIBRE, "DIET_CEREAL_FIBRE" } };
}

我需要能够从debugBoot.js中完成这些工作 一旦我按下按钮(调试模式下的色氨酸f12),我跳进debugBoot.js并通过f10的行和当我来到行

var data=rest.responseText;

数据是空的...... 当我继续上线时

 var jsonResponse = JSON.parse(data);

出现错误:

VM5402:1 Uncaught SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at Object.dss.getParameters (debugBoot.js:11)
at HTMLButtonElement.onclick (debug.html?scriptId=2:18)

我忘了说: 一旦我继续这个链接:

http://localhost:8080/MW-war/rest/mw/enumerateParams

我将此作为输出:

[["0","PATIENT_ID"],["1","AGE"],["2","BLOOD_PRESSURE"],["3","GENDER"],["4","SMOKING_HABITS"],["5","DIET_FRUITS_VEGGIES"],["6","CHOLESTEROL"],["7","ALCOHOL"],["8","ACTIVITY"],["9","QUIT_SMOKING"],["10","DIET_CEREAL_FIBRE"]]

我搜索了很多,发现一些不太相似的问题,但没有什么太类似于我的问题......有什么建议吗?

1 个答案:

答案 0 :(得分:0)

dss.getParameters = function(){
    var rest=new XMLHttpRequest();
    rest.open("GET", "http://localhost:8080/MW-war/rest/mw/enumerateParams", false);
    rest.send(null);
    if (rest.status === 200) {
      console.log(rest.responseText);
    }
    return JSON.parse(rest.responseText);
};

这很有用......很多...现在我有一个类似的POST方法任务:)

按下按钮后,我得到了希望的结果

希望这有助于将来的某些人;)