AJAX请求跨域问题的解决方案

当前位置:首页 » 前端
In 笔记  @2018-04-24

这个问题其实刚入行的时候就碰到了,后来就在接口返回数据返回的函数里加了一行代码:

header("Access-Control-Allow-Origin: *");

一直想总结一下这个让很多新手困扰的跨域问题,现在来说一说。
首先,跨域产生的原因大家可以自行百度。
本地测试从http://localhosthttp://192.168.50.88域请求数据。

测试代码:

前台代码:

$.get('http://192.168.50.88/tp_test/Home/Test/test_jsonp', function(data) {
    console.log(data);
});

后台代码:

public function test_jsonp(){
    $data = json_encode(array(
        'uid'=>5465,
        'nick'=>'刘德华1265'
    ));
    echo $data;
}

在不做任何处理的情况下浏览器会提示跨域权限问题的,无法获取到数据。

Failed to load http://192.168.50.88/tp_test/Home/Test/test_jsonp: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access

解决方案

方案一:JSONP

这个方案虽然很古老,但依然有效,对于小型的GET请求任务还是可以胜任的,原理很取巧,理解它还是很有必要的;
他的原理就是,通过向页面添加<script></script>标签,加载接口,后台接口按照约定好的将数据放到接口中获取到的callback函数中,前台通过这个函数运行来获取到数据。
代码修改如下:
前台代码:

// callback函数叫jsonp_callback
$(document).ready(function() {
    CreateScript('http://192.168.50.88/tp_test/Home/Test/test_jsonp?callback=jsonp_callback');
});
// callback函数jsonp_callback
function jsonp_callback(data){
    console.log(data);
}
// 添加script标签
function CreateScript(src){  
    $("<script><//script>").attr("src", src).appendTo("body");
} 

后台代码:

public function test_jsonp(){
    $callback = $_GET['callback'];
    $data = json_encode(array(
        'uid'=>5465,
        'nick'=>'刘德华1265'
    ));
    echo "{$callback}({$data})";
}

可以看到,已经可以正确的将数据获取到了,这也就是JSONP的实现过程,由于这样的实现原理,导致了JSONP的两个问题:
1. 需要后台配合返回约定格式的数据。
2. JSONP只能发送GET请求。
而在使用Jquery封装好的jsonp请求时,就会更加方便一些了,同样的后端代码,前端代码就可以做简化了:

$.ajax({
    url: 'http://192.168.50.88/tp_test/index.php/Home/Test/test_jsonp',
    dataType: 'jsonp',
    jsonp:'callback',
})
.done(function(data) {
    console.log(data);
})

Jquery的封装帮我们完成了所有前台需要完成的工作,只需要后台将数据放到callback中返回就可以了。
由于JSONP只能发送GET请求,其他的场景就需要第二种方案;

方案二:HTTP访问控制(CORS)

CORS是一个W3C标准,全称是”跨域资源共享”Cross-origin resource sharing。它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。
CORSJSONP的使用目的相同,但是比JSONP更强大。JSONP只支持GET请求,CORS支持所有类型的HTTP请求。JSONP的优势在于支持老式浏览器,以及可以向不支持CORS的网站请求数据。
CORS的用法很简单:我们只需要的被请求的接口的回复头中添加:

// 星号表示所有的域都可以请求这里的数据
Access-Control-Allow-Origin: *
//或者指定域,例如上面的测试中我们需要加入即可正常得到数据了
Access-Control-Allow-Origin: http://localhost

关于CORS更多的设置和用法请自行搜索。

标签: , , , , ,   评论: 1枚 

JS获取数组的最大值和最小值

当前位置:首页 » 前端
In 笔记  @2017-03-30

需求:

高德轨迹返回的字符串为一连串的坐标点及海拔等数据,现在需要计算所有坐标点海拔最大落差;
也就是海拔的最大值和最小值的差值。
接口返回的json数据result是这样的:

{
    "id":0,
    "msg":"获取数据",
    "data":{
        "id":"2246",
        "record_id":"1",
        "startpoint":"29.012560221354168,120.47038384331597,gps,1490840902590,0.0,306.11",
        "endpoint":"29.011363,120.471702,gps,1490841850974,0.0,404.71",                    
        "pathline":"29.012560221354168,120.47038384331597,gps,1490840902606,0.0,306.11;29.01255425347222,120.47040256076389,gps,1490840905591,0.0,309.87;29.012554796006945,120.47040635850695,gps,1490840908583,0.0,312.38;29.01253824869792,120.47041314019097,gps,1490840911591,0.0,314.79;29.01252007378472,120.47042507595486,gps,1490840914608,0.0,314.65;29.01252007378472,120.47042507595486,gps,1490840917643,0.0,312.49;29.01251681857639,120.47042507595486,gps,1490840920586,0.39,311.22;29.012509223090277,120.47042236328124,gps,1490840923603,0.26,311.05;29.012479654947917,120.4704248046875,gps,1490840926583,1.05,311.11;29.01244384765625,120.47043891059027,gps,1490840929603,1.17,311.09;29.012423502604168,120.47045003255208,gps,1490840932589,1.06,311.03;29.01241021050347,120.4704652235243,gps,1490840935589,1.0,311.17;29.012403428819443,120.47046983506945,gps,1490840938608,0.92,311.55;29.012401801215276,120.47048963758681,gps,1490840941609,0.92,311.8;29.012410481770832,120.47051595052083,gps,1490840944610,0.9,311.75;29.01242513020833,120.47055284288194,gps,1490840947602,0.93,311.54;29.012442762586804,120.47056830512153,gps,1490840950592,0.87,311.39;29.012456868489583,120.47059326171875,gps,1490840953581,0.86,311.18;29.012467719184027,120.47059868706597,gps,1490840956594,0.62,311.0;29.012483452690972,120.4706165907118,gps,1490840959599,0.57,310.9;29.0125146484375,120.47065565321181,gps,1490840962600,1.01,310.85;29.01253200954861,120.4706787109375,gps,1490840965590,1.01,310.82;29.012550184461805,120.4707066514757,gps,1490840968591,0.94,310.82;29.01257378472222,120.47071831597222,gps,1490840971590,0.9,310.91;29.012590874565973,120.47073432074653,gps,1490840974587,0.88,310.97;29.01260064019097,120.47074245876736,gps,1490840977610,0.86,310.98;29.012616916232638,120.47076904296875,gps,1490840981592,0.63,310.95;29.01262234157986,120.47078342013889,gps,1490840984601,0.55,311.05;29.012636990017363,120.47081081814235,gps,1490840987587,0.79,311.31;29.012650282118056,120.4708251953125,gps,1490840990590,0.63,311.81;29.012664116753474,120.47084065755209,gps,1490840993587,0.67,312.35;29.01266899956597,120.47085693359375,gps,1490840996607,0.36,312.81;29.012671712239584,120.47087673611111,gps,1490840999585,0.32,313.29;29.01267822265625,120.47088785807291,gps,1490841002585,0.33,313.99;29.012677680121527,120.47089545355902,gps,1490841005585,0.14,314.49;29.012679036458334,120.47088758680556,gps,1490841008594,0.49,314.83;29.012674153645833,120.47088568793403,gps,1490841011591,0.06,315.02;",
        "travel_notes_title":"# 步行 # ",
        "travel_notes_img_count":"4",
        "distance":"1.913",
        "averagespeed":"7.26",
        "duration":"948",
        "audio_count":"0",
        "video_count":"0",
        "kacl":"66"
    }
}

result数据中的pathline轨迹坐标点数据只截取了一部分,js数据处理代码如下:

    var pathline = result.data.pathline;
    var info_arr = pathline.split(';');
    var altitude = [];// 海拔数据集合
    var point_arr = [];// 坐标点集合
    for(i=0;i<info_arr.length-1;i++){
        var arr = info_arr[i].split(',');
        point_arr[i] = [arr[1],arr[0]];
        altitude[i] = arr[5];
    }
    console.log(altitude);
    console.log(Math.max.apply(null, altitude));
    console.log(Math.min.apply(null, altitude));
    //计算海拔最大落差
    var high = Math.max.apply(null, altitude) - Math.min.apply(null, altitude);
    high = high.toFixed(2);

altitude为包括全部坐标点的数据集合;
获取最大值Math.max.apply(null, altitude),最小值使用Math.max.apply(null, altitude)

输出的结果是:

["306.11", "309.87", "312.38", "314.79", "314.65", "312.49", "311.22", "311.05", "311.11", "311.09", "311.03", "311.17", "311.55", "311.8", "311.75", "311.54", "311.39", "311.18", "311.0", "310.9", "310.85", "310.82", "310.82", "310.91", "310.97", "310.98", "310.95", "311.05", "311.31", "311.81", "312.35", "312.81", "313.29", "313.99", "314.49", "314.83", "315.02"]
315.02
306.11
标签: , ,   评论: JS获取数组的最大值和最小值已关闭评论 

JS实现HTML静态页面URL跳转传值

当前位置:首页 » 前端
In 笔记  @2016-10-20

在跳转的url里面加入参数,格式如下:

http://www.abc123.com/index.html?page=12&id=525

其中,”?”后面为键值对,”=”左边是键,右边是值。

写一个截取url获取参数的方法。

/**
 * 获取url传过来的参数
 * @return  array
 */
function getRequest() {  
    var url = location.search; //获取url中"?"符后的字串   
    var theRequest = new Object();  
    if (url.indexOf("?") != -1) {  
        var str = url.substr(1);  
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {  
            theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
        }  
    }else{
    theRequest = null;
    }
    return theRequest;
}

在跳转后的页面调用这个getRequest()方法,即可获取到数据了。

var GET = getRequest();
if(GET){
    var page = GET.page, id = GET.id;
}
console.log("获取到的数据:page=" + page + "-------id=" + id);
标签: , ,   评论: JS实现HTML静态页面URL跳转传值已关闭评论