参考:http://stackoverflow.com/questions/5892569/responding-with-a-json-object-in-nodejs-converting-object-array-to-json-string
服务器用nodejs写,创建一个服务器监听具体url并用回调函数处理,返回json数据。(nodejs基础见【nodejs】imooc上的学习笔记)
代码示例:
客户端html:
addonclick me!
...
const hostname = '127.0.0.1';
const port = 1337;
$(function(){
$("button").bind("click",function(){
var url = "http://" + hostname + ":" + port;
$.ajax({
url:url,
dataType:"jsonp",
jsonp:"callback",
jsonpCallback:"success_jsonpCallback"
}).done(function(data) {
$("p").html(data.toString);
});
});
});
nodejs服务器:
const http = require('http');
const addon = require('./build/Release/addon');//调c++方法引入的
const hostname = '127.0.0.1';
const port = 1337;
http.createServer((req, res) => {
res.writeHead(200, {"Content-Type": "application/json"});
var otherArray = ["item1", "item2"];
var otherObject = { item1: "item1val", item2: "item2val" };
var json = JSON.stringify({
anObject: otherObject,
anArray: otherArray,
another: addon.hello()//c++文件中暴露的方法
});
res.end("success_jsonpCallback(" + json + ")");//!!一定要加配置的回调方法名
// res.writeHead(200, { 'Content-Type': 'text/plain' });
// res.end(addon.hello());
}).listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
}); 记得先起服务器,在按网页上的按钮。