刘怀宇
1.将cppcms-0.99.10/examples/json_rpc/rpc.cpp文件中的json_service类拷贝到
examples/templates/hello-tmpl.cpp 中
2.修改hello-tmpl.cpp 中的main函数,添加两个服务
int main(int argc,char ** argv) { try { cppcms::service srv(argc,argv); srv.applications_pool().mount(cppcms::applications_factory<my_hello_world>() , cppcms::mount_point(std::string("/html")) ); srv.applications_pool().mount(cppcms::applications_factory<json_service>() , cppcms::mount_point(std::string("/jsonrpc")) ); srv.run(); } catch(std::exception const &e) { std::cerr<<e.what()<<std::endl; } }
{ "service" : { "api" : "http", "port" : 8080 }, "http" : { "script_names" : ["/jsonrpc","/html"] } }
<html> <body> <script type="text/javascript"> function call() { var xhr = new XMLHttpRequest(); xhr.open("post", 'http://localhost:8080/jsonrpc'); // Required by JSON-RPC over HTTP xhr.setRequestHeader("Content-Type","application/json"); // It is better to use real formatter like JSON.js x=parseInt(document.getElementById('x').value); y=parseInt(document.getElementById('y').value); var request = '{"method":"div","params":[' + x + ',' + y +'],"id":1}'; xhr.onreadystatechange = function() { if (xhr.readyState === 4) { res = 'Unknown Error'; if(xhr.status === 200) { // Don't call eval in real code use some parser var result = eval('(' + xhr.responseText + ')'); if(result.error==null) { res = result.result; } else { res = result.error; } } document.getElementById('result').innerHTML = res; } } xhr.send(request); return false; } </script> <form onsubmit="return call();"> <p> <input type="text" id="x" /> <input type="submit" value="/" /> <input type="text" id="y" /> = <span id="result"></span> </p> </form> </body> </html>
7. 访问http://localhost:8080/html 在返回的html页面中计算除法,即可成功访问后台的json服务,得到结果
8.注意,IE6不支持JSON_RPC技术。