【发布时间】:2017-11-27 09:09:05
【问题描述】:
我的网页中有这个JavaScript 代码:
const configDefault = {
Bot: {
// initial sessionAttributes
sessionAttributes: {},
},
};
现在我想要的是设置sessionAttributes 与用户打开此网页的设备的ip address。基于this SO post,我编写了这段代码来获取设备的ip address,但是我在首先从返回的json 对象中提取ip address,然后集成这部分以便sessionAttributes 在我的上面的代码是用ip address设置的:
function myIP() {
$.getJSON('//freegeoip.net/json/?callback=?', function(data) {
JSON.stringify(data, null, 2));
});
}
上述代码中的json 对象返回以下示例结构。我想从中取出 ip 字段,并在顶部的代码中将其设置为 sessionAttributes:
{
"ip": "116.12.250.1",
"country_code": "SG",
"country_name": "Singapore",
"region_code": "01",
"region_name": "Central Singapore Community Development Council",
"city": "Singapore",
"zip_code": "",
"time_zone": "Asia/Singapore",
"latitude": 1.2931,
"longitude": 103.8558,
"metro_code": 0
}
我是 JavaScript 新手,所以我无法找到一种方法来做到这一点。谁能帮助我以正确的方式构建这种结构?
更新:我当前的代码位于 http://js.do/code/158408 。运行 $ 符号时出现错误
const configDefault = {
Bot: {
// initial sessionAttributes
sessionAttributes: {},
},
};
function myIP() {
$.getJSON('//freegeoip.net/json/?callback=?', function(data) {
return JSON.parse(data);
});
}
const ipInformation = myIP();
configDefault.Bot.sessionAttributes.ip = ipipInformation.ip;
【问题讨论】:
标签: javascript json ip-address