cpp-httplip github
service code
#include "http_service.h"
#include "../json/include/nlohmann/json.hpp"
#include <iostream>
#include <sstream>
using namespace std;
using json = nlohmann::json;
void string2num(string str, double &num)
{
stringstream ss;
ss << str;
ss >> num;
}
int main(void)
{
using namespace httplib;
Server svr; // 創建服務器對象
svr.set_base_dir("../../http_service");
// 網址根目錄,你看httplib源碼會發現 首頁默認爲index.thml
svr.Get("/add", [](const Request& req, Response& res) {
json j; // json用於信息傳遞
double a, b;
string2num(req.get_param_value("a").c_str(), a);
string2num(req.get_param_value("b").c_str(), b);
double ans = a + b;
j["ans"] = ans;
res.set_content(j.dump(), "text/plain");
//res.set_content_provider();
});
svr.listen("localhost", 3333); // 啓動服務
}
效果很簡陋,前端不會QAQ
html code
<html>
<head>
<meta charset="utf-8">
<title>multiply</title>
</head>
<body>
<form id = "form1">
A: <input type="text" name="a" placeholder="數字A" id = "A"><br>
B: <input type="text" name="b" placeholder="數字B" id = "B"><br>
ans: <div type="text" name = "ans" id = "ans"></div><br>
<input type="submit" value="提交" id = "submit">
</form>
<p>點擊"提交"按鈕,表單數據將被髮送到服務器上的“add”程序上。</p>
</body>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
$("#submit").on("click",function(){
var a = $("#form1 input:eq(0)").val();
var b = $("#form1 input:eq(1)").val();
$.ajax({
//幾個參數需要注意一下
type: "GET",//方法類型
dataType: "json",//預期服務器返回的數據類型
url:"add" ,//url
data: {"a":a,"b":b},
success: function (result) {
$("#ans").text(result.ans);
console.log(result.ans);//打印服務端返回的數據(調試用)
if (result.resultCode == 200) {
alert("SUCCESS");
};
},
error : function() {
alert("異常!");
}
});
return false;
})
</script>
</html>
目錄結構
json庫
。。。算了json就是最大的文件夾了,我還是把整個項目放github上吧