栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

node.js解析请求的JSON

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

node.js解析请求的JSON

在服务器端,您将接收jQuery数据作为请求参数,而不是JSON。如果您以JSON格式发送数据,您将收到JSON并且需要对其进行解析。就像是:

$.ajax({    type: 'GET',    url: 'door.validate',    data: {        jsondata: "{ "foo": "bar", "foo2": 3 }"        // or jsondata: JSON.stringify(credentials)   (newest browsers only)    },    dataType: 'json',    complete: function(validationResponse) {        ...    }});

在服务器端,您将执行以下操作:

var url = require( "url" );var queryString = require( "querystring" );http.createServer(    function (req, res) {        // parses the request url        var theUrl = url.parse( req.url );        // gets the query part of the URL and parses it creating an object        var queryObj = queryString.parse( theUrl.query );        // queryObj will contain the data of the query as an object        // and jsonData will be a property of it        // so, using JSON.parse will parse the jsonData to create an object        var obj = JSON.parse( queryObj.jsonData );        // as the object is created, the live below will print "bar"        console.log( obj.foo );    }).listen(80);

要将对象序列化为JSON并在jsonData中设置值,可以使用

JSON.stringify(credentials)
(在最新的浏览器中)或JSON-js。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/485005.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号