我想获得' http://localhost:8080/api/printer?exclude=temperature'提供的Json数据。 [HTTP / 1.1]。
这是要提供的Json数据。
{
"state": {
"text": "Operational",
"flags": {
"operational": true,
"paused": false,
"printing": false,
"sdReady": true,
"error": false,
"ready": true,
"closedOrError": false
}
}
}
类型是' GET'和Content-Type是' application / json'
以下是我的JSP完整源代码。
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript" language="javascript">
function print_stat(){
jQuery.ajax({
type: 'GET',
async: false ,
url: 'http://localhost:8080/api/printer?exclude=temperature&apikey=1234567...',
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert("TEST");
},
error : function(x, e) {
alert('server error occoured');
if(x.status==0){ alert('0 error');
}else if(x.status==404){ alert('404 error');
}else if(x.status==500){ alert('500 error');
}else if(e=='parsererror'){ alert('Error.nParsing JSON Request failed.');
}else if(e=='timeout'){ alert('Time out.');
}else { alert(x.responseText); }
}
});
}
</script>
<body>
<input type="button" onclick="print_stat()" value="test">
</body>
我无法看到&#34; TEST&#34;弹出窗口。 没有任何事情发生。
我该怎么做才能获取数据?
请帮帮我。
答案 0 :(得分:1)
你能试试吗,
<强>语法:强>
$.ajax({
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
type: "POST",
url: uri,
data: jsonStrJson,
dataType: "json",
success: function(json){
console.log(json);
}
});
您的代码应该像100%正常运行且经过测试的代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript" language="javascript">
function print_stat(){
jQuery.ajax({
type: 'GET',
async: false ,
url: 'http://localhost:8080/api/printer?exclude=temperature&apikey=1234567...',
dataType: 'json',
success: function (data) {
alert("TEST");
console.log(data);
},
error : function(x, e) {
alert('server error occoured');
if(x.status==0){ alert('0 error');
}else if(x.status==404){ alert('404 error');
}else if(x.status==500){ alert('500 error');
}else if(e=='parsererror'){ alert('Error.nParsing JSON Request failed.');
}else if(e=='timeout'){ alert('Time out.');
}else { alert(x.responseText); }
}
});
}
</script>
<body>
<input type="button" onclick="print_stat()" value="test">
</body>
</body>
</html>