我正在使用 POST 从使用 angularjs 的点击事件中获取数据。我想我已经编写了大部分代码,但在运行查询时出现“无效字符”错误。我认为这可能与我从 javascript 中获取变量时的类型转换有关。
这是我的 java 文件的帖子
@POST
@Path("module")
@Consumes(MediaType.APPLICATION_JSON)
public List<ModuleProcCount> getInput(int jobId) throws IOException{
try (Dbc dbc = vehmPool.getDbc()){
List<ModuleProcCount> pusher = statements.inMod(dbc, jobId);
return pusher;
}
}
这里是函数或者我的帖子
$scope.sendJobId = function(jobId) {
$http.post("rest/performance/module", jobId).then(function(response){
$scope.pusher = response.data;
for (var i = 0; i < $scope.pusher.length; i++) {
var p = $scope.puller[i];
console.log("modName: " + p.modName);
console.log("modClass: " + p.cellClass);
console.log("modData: " + p.modCount);
}
});
这是我的 HTML,其中包含 Angular 代码。
<table id="Table" class="JobID-table" style="text-align:center" >
<tr class="table-Header">
<th>JOB ID</th>
<th>TIME FOR ALL MODULES(MILLISECONDS)</th>
</tr>
<tr class="jobID-Table-tr" ng-repeat="p in puller | orderBy : '-modCount'">
<td ng-click="sendJobId(p.modName)" class={{p.cellClass}}>
{{p.modName}}
</td>
<td class={{p.cellClass}}>
{{p.modCount}}
</td>
</tr>
</table>
最佳答案
您的 Java 方法设置为使用 JSON (@Consumes(MediaType.APPLICATION_JSON)
)。这意味着 JAX-RS 正在尝试将您的 POST 请求的主体解析为 JSON 对象,然后将其映射到您的使用者函数的参数类型,在本例中为 String
。
由于您实际上并没有在 POST 请求中发送 JSON 对象,因此您应该告诉 JAX-RS 您希望从负载中接收原始文本:
@Consumes(MediaType.TEXT_PLAIN)
或者,您可以使用 JSON!因为你提到你的参数是一个整数,这个例子使用一个 JSON 对象和一个名为 jobId
的整数参数:
/**
* This class is used by JAX-RS to parse to and from JSON. The field
* names used here (and by extension the getters and setters) should
* match those used in your JSON.
*/
class InputRequest {
int jobId;
public String getJobId() {
return jobId;
}
public void setJobId(int jobId) {
this.jobId = jobId;
}
}
@POST
@Path("module")
@Consumes(MediaType.APPLICATION_JSON)
public List<ModuleProcCount> getInput(InputRequest reqPayload) throws IOException {
int jobId = reqPayload.getJobId();
}
在客户端,angular 会自动将传递给负载的对象转换为 JSON 字符串,并为您设置 Content-type
header (ref)。
$http.post('rest/performance/module', {
jobId: 123456
});
关于javascript - 使用 Ajax 将 var 发送到查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53636016/