参考:http://stackoverflow.com/questions/5892569/responding-with-a-json-object-in-nodejs-converting-object-array-to-json-string
客户端用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="http://libs.baidu.com/jquery/1.9.0/jquery.js" 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 = "http://" + hostname + ":" + port;
$.ajax({
url:url,
dataType:"jsonp",
jsonp:"callback",
jsonpCallback:"success_jsonpCallback"
}).done(function(data) {
$("p").html(data.toString);
});
});
});
</script>
</body>
</html>
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 http://${hostname}:${port}/`);
});
记得先起服务器,在按网页上的按钮。
本文介绍如何使用Node.js建立一个服务器,监听特定URL并返回JSON数据。客户端通过AJAX请求该URL,但遇到了jQuery.ajax()的SyntaxError。在服务器端,我们展示了如何将对象数组转换为JSON字符串并发送给客户端。

1万+

被折叠的 条评论
为什么被折叠?



