Skip to content

Instantly share code, notes, and snippets.

@yuu-nkjm
Created January 16, 2015 09:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuu-nkjm/f821946b120fb23779c4 to your computer and use it in GitHub Desktop.
Save yuu-nkjm/f821946b120fb23779c4 to your computer and use it in GitHub Desktop.
JSONRPCのサービスをポーリングするときはこんな感じでどうだろうか.
function pollService(url, method, params, callback) {
var ajaxReq = null;
var error = false;
function refresh(url, method, params, callback) {
var methodCall = {method : method, params : params};
ajaxReq = $.ajax({
type : "POST", dataType : "json",
url : url,
data : JSON.stringify(methodCall),
timeout : 3000,
success : callback,
error : function(XMLHttpRequest, textStatus, errorThrown){
error = true;
alert("エラーが発生しました.処理を停止します.");
},
complete: function(){
ajaxReq = null;
if(!error){
setTimeout(function(){refresh(url, method, params, callback)}, 1000);
}
}
});
}
setTimeout(function(){refresh(url, method, params, callback)}, 1000);
}
$(function() {
var url = "http://localhost:8080/jsonrpc/services/TrafficSimulatorService";
callService(url, "startSimulation", [],
function(data, dataType) {
var pid = data.result;
console.log(pid);
var params = [pid, 0];
callService(url, "getRoadData", [pid, 0],
function(data, dataType) {
console.log(JSON.stringify(data));
pollService(url, "getVehicleData", params,
function (data, dataType) {
params[1]+=1;
console.log(JSON.stringify(data));
});
});
});
});
function printOut(data, dataType) {
$("#result").append(
"<div>" + dataType + "<br>" + JSON.stringify(data.result) + "</div><hr>");
}
function callService(url, method, params, callback) {
var methodCall = {method : method, params : params};
$.ajax({
type : "POST", dataType : "json",
url : url,
data : JSON.stringify(methodCall),
timeout : 3000,
success : callback
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment