【发布时间】:2011-06-17 13:07:16
【问题描述】:
Restful 服务(来自服务器)
@GET
@Produces("application/json")
@Consumes("application/json")
@Path("/getStatus/")
// server:8080/server/rest/admin/status/whatSoEver
public void getStatus(
@Context HttpServletRequest request,
@Context HttpServletResponse response) throws ServletException,
IOException
{
//create the JSON Object to pass to the client
JSONObject object=new JSONObject();
response.setContentType("text/javascript");
String callback = request.getParameter("jsoncallback");
try
{
for (Server i : svr)
{
object.put("name",getName());
object.put("status",getStatus());
}
}
catch(Exception e)
{
throw new ServletException("JSON Hosed up");
}
String json = object.toString();
/*response.getOutputStream().println(callback + "(" + json + ");");*/
response.getOutputStream().print(json);
response.flushBuffer();
System.out.println("Sending "+json);
}
在客户端
<script>
$(document).ready(function()
{
function myFunc()
{
$.getJSON("http://localhost:8080/MyWebApp/getStatus",
function (json)
{
$('#refreshMe').replaceWith(json.status);
/* alert("Server name: " + json.name + "Server Status:"+json.status); */
});
}
myFunc();
});
/*Do a refresh every 2 seconds */
setInterval( "myFunc()", 500 );
</script>
如何让这个 jquery ajax 调用 行为和上面一样吗?
<script>
$.ajaxSetup ({ cache: false });
$.ajax
({
url: "http://localhost:8080/MyWebApp/getStatus",
dataType: 'json',
data: "???",
success: ???
});
</script>
【问题讨论】:
-
请不要将
setInterval与字符串一起使用,而是使用函数指针:setInterval(myFunc, 500);或setInterval(function(){ /*some code*/ }, 500);此外,您可能希望在前一个请求完成而不是更早时开始新请求。 -
嗨,这是我想做的一个很好的例子。您使用哪些 Java 库来构建 REST 服务?
标签: javascript jquery ajax jsp