獲取IP,並存儲的步驟:
1.通過瀏覽器的ip獲取方法采用第三方的搜狐IP查詢,使用方法如下:
- 在根據情況引入js文件,一般在根目錄下的index,html中進行引入(public====》index.html)
<script src="http://pv.sohu.com/cityjson?ie=utf-8"></script>
- 獲取數據
<script type="text/javascript">
sessionStorage.setItem('ip',returnCitySN["cip"]);
sessionStorage.setItem('cname',returnCitySN['cname'])
</script>
2.在對應的頁面中進行數據的拿取,和向后台進行發送進行存儲,以便后續使用(先向后台請求,如果數據不存在,在請求另一個第三方的數據(電信/聚合---都是收費)的)
因為有js的存在,一般是放在mounted()頁面中進行操作:
接收數據:let that= this ;
that.checkIp = sessionStorage.getItem('ip'); checkIp是需要現在data中進行聲明的
先向后台進行請求,調用后台給出的接口,根據后台返回的值做判斷,如果有值則不再請求第三方的數據直接進行數據展示,沒有則進行數據請求,在進行數據獲取展示
xxx(this.checkIp).then((res)=>{
if(res.data.enName == 'new User'){
ajax({
'url':'https://api.ip138.com/ip/',
'data':{ //默認自動添加callback參數
'ip':this.checkIp, //為空即為當前iP地址
'oid':'48260',
'mid':'108510',
'token':'9681975f8b86df4f9d47cc6d68a230ef' //不安全,請定期刷新token,建議進行文件壓縮
},
'dataType':'jsonp',
'success':function(res){
console.log(res);
}
});
}else if(res.data.enName != ''){
xxx(this.checkIp).then((res)=>{
that.form.countryName = res.data.enName;
})
}
})
3.當使用第三方的數據請求成功的時候,你需要讓數據傳給后台(避免一個id頻繁,多次的調用,占用資源,惡意使用)
if(res.ret == 'ok'){
console.log(11111);
// console.log(this);
that.form.countryName = res.data[0];
// console.log(that.form.countryName,"that.form.countryName");
// console.log("this.choseCountry",this.choseCountry);
that.Allparams.ip = that.checkIp;
that.Allparams.enName = that.form.countryName;
xxx(that.Allparams).then((res)=>{
console.log(res);
})
}
完整的代碼是:
// 獲取ip,並向后台查詢
(xxx是代表的數據向后台請求的函數名,注意引入接口路徑)
let that = this;
that.checkIp = sessionStorage.getItem('ip');
console.log(that.checkIp+" " +that.checkCity);
xxx(this.checkIp).then((res)=>{
if(res.data.enName == 'new User'){
ajax({
'url':'https://api.ip138.com/ip/',
'data':{ //默認自動添加callback參數
'ip':this.checkIp, //為空即為當前iP地址
'oid':'48260',
'mid':'108510',
'token':'9681975f8b86df4f9d47cc6d68a230ef' //不安全,請定期刷新token,建議進行文件壓縮
},
'dataType':'jsonp',
'success':function(res){
console.log(res);
if(res.ret == 'ok'){
console.log(11111);
// console.log(this);
that.form.countryName = res.data[0];
// console.log(that.form.countryName,"that.form.countryName");
// console.log("this.choseCountry",this.choseCountry);
that.Allparams.ip = that.checkIp;
that.Allparams.enName = that.form.countryName;
xxx(that.Allparams).then((res)=>{
console.log(res);
})
}
}
});
}else if(res.data.enName != ''){
xxx(this.checkIp).then((res)=>{
that.form.countryName = res.data.enName;
})
}
})
使用第三的數據的時候還需要使用第三的js,js如下:(根據自己情況引入,一般存放在piblic ====>index.html中)
function ajax(params){
params = params||{};
if (!params.url) {
throw new Error('Necessary parameters are missing.'); //必要參數未填
}
var random = +new Date;
var hander = null;
var options = {
url: '', //接口地址
type: 'GET', //請求方式
timeout: 5000, //超時等待時間
cache: true, //緩存
async: true, //是否異步
xhrFields: {}, //設置XHR對象屬性鍵值對。如果需要,可設置withCredentials為true的跨域請求。
dataType: 'json', //請求的數據類型
data: {}, //參數
jsonp: 'callback', //傳遞請求完成后的函數名
jsonpCallback: 'jsonp_' + random, //請求完成后的函數名
error: function() {}, //請求失敗后調用
success: function(){}, //請求成功后調用
complete: function(){} //請求完成后調用
};
var formatParams = function(json) {
var arr = [];
for(var i in json) {
arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(json[i]));
}
return arr.join("&");
};
for(var i in params){
switch(i){
case 'type':
options[i] = params[i].toUpperCase();
break;
case 'dataType':
options[i] = params[i].toLowerCase();
break;
default:
options[i] = params[i];
}
}
if(typeof options.data =='object'){
options.data = formatParams(options.data);
}
if(options.dataType=='jsonp'){
options.cache = params.cache||false;
//插入動態腳本及回調函數
var $head = document.getElementsByTagName('head')[0];
var $script = document.createElement('script');
$head.appendChild($script);
window[options.jsonpCallback] = function (json) {
$head.removeChild($script);
window[options.jsonpCallback] = null;
hander && clearTimeout(hander);
options.success(json);
options.complete();
};
//發送請求
if(options.cache){
options.data += options.data?'&_'+random:'_'+random;
}
options.data += '&'+options.jsonp+'='+options.jsonpCallback;
$script.src = (options.url + '?' + options.data).replace('?&','?');
//超時處理
hander = setTimeout(function(){
$head.removeChild($script);
window[options.jsonpCallback] = null;
options.error();
options.complete();
}, options.timeout);
}else{
if(options.cache){
options.data += options.data?'&_'+random:'_'+random;
}
//創建xhr對象
var xhr = new (self.XMLHttpRequest||ActiveXObject)("Microsoft.XMLHTTP");
if(!xhr){
return false;
}
//發送請求
if (options.type == 'POST') {
xhr.open(options.type, options.url, options.async);
xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
}else{
options.url += options.url.indexOf('?')>-1?'&'+options.data:'?'+options.data;
xhr.open(options.type, options.url, options.async);
options.data = null;
}
if(options.xhrFields){
for(var field in options.xhrFields){
xhr[field]= options.xhrFields[field];
}
}
xhr.send(options.data);
//超時處理
var requestDone = false;
hander = setTimeout(function() {
requestDone = true;
if(xhr.readyState != 4){
xhr.abort();
options.error();
}
options.complete();
}, options.timeout);
//狀態處理
xhr.onreadystatechange = function(){
if(xhr.readyState == 4&&!requestDone) {
if(xhr.status>=200 && xhr.status<300||xhr.status == 304) {
var data = options.dataType == "xml" ? xhr.responseXML : xhr.responseText;
if (options.dataType == "json") {
try{
data = JSON.parse(data);
}catch(e){
data = eval('(' + data + ')');
}
}
options.success(data);
} else {
options.error();
}
hander && clearTimeout(hander);
options.complete();
}
};
}
}