nodejs 前端 返回数组给_【nodejs】服务器处理url请求并返回json数据

参考: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:

addon

click 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}/`);

}); 记得先起服务器,在按网页上的按钮。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值