I have this JavaScript
code in my webpage:
const configDefault = {
Bot: {
// initial sessionAttributes
sessionAttributes: {},
},
};
Now What I want is to set the sessionAttributes
with the ip address
of the device on which this webpage is opened by the user. Based on this SO post I wrote this code to get the ip address
of the device but I am having issue in first extracting the ip address
out of the returned json
object and then integrating this piece so that sessionAttributes
in my code above is set with the ip address
:
function myIP() {
$.getJSON('//freegeoip.net/json/?callback=?', function(data) {
JSON.stringify(data, null, 2));
});
}
The json
object in above code return following sample structure. I want to get ip
field out of it and set it to sessionAttributes
in my code at the top:
{
"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
}
I am new to JavaScript so I am unable to find a way to do this. Can anyone help me in structuring this right way?
Update: My current code is at http://js.do/code/158408 . I am getting error on $
sign when I run it
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;
You should use JSON.parse instead of stringify.
const ipInformation = JSON.parse(data);
console.log(ipInformation.ip);
const configDefault = {
Bot: {
// initial sessionAttributes
sessionAttributes: {},
},
};
configDefault.Bot.sessionAttributes.ip = ipipInformation.ip;
console.log(configDefault);
or if you wanted all of ipInformation in sessionAttributes.
configDefault.Bot.sessionAttributes = ipipInformation;
As $.getJSON is async, you'll need to do all the work inside the callback:
let configDefault = {
Bot: {
// initial sessionAttributes
sessionAttributes: {}
}
};
function myIP(configDefault) {
$.getJSON("//freegeoip.net/json/?callback=?", function(data) {
const ipInformation = JSON.parse(data);
configDefault.Bot.sessionAttributes.ip = ipInformation.ip;
console.log(configDefault);
return configDefault;
});
}
configDefault = myIP(configDefault );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.