参考:
客户端用ajax获取url返回的json,具体问题见【error】jQuery.ajax()报错Uncaught SyntaxError: Unexpected token
服务器用nodejs写,创建一个服务器监听具体url并用回调函数处理,返回json数据。(nodejs基础见【nodejs】imooc上的学习笔记)
代码示例:
客户端html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>addon</title> <script src="" type="text/javascript"></script> </head> <body> <div> <button>click me!</button> <p>...</p> </div> <script type="text/javascript"> const hostname = '127.0.0.1'; const port = 1337; $(function(){ $("button").bind("click",function(){ var url = "" + hostname + ":" + port; $.ajax({ url:url, dataType:"jsonp", jsonp:"callback", jsonpCallback:"success_jsonpCallback" }).done(function(data) { $("p").html(data.toString); }); }); }); </script> </body> </html>
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()<span style="white-space:pre"> </span>//c++文件中暴露的方法
});
res.end("success_jsonpCallback(" + json + ")");<span style="white-space:pre"> </span>//!!一定要加配置的回调方法名
// res.writeHead(200, { 'Content-Type': 'text/plain' });
// res.end(addon.hello());
}).listen(port, hostname, () => {
console.log(`Server running at ${hostname}:${port}/`);
});
记得先起服务器,在按网页上的按钮。