Loading

jQuery跨域

直接上代码,复制粘贴即可

HTML代码(localhost/index.html)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.js"></script>
</head>
<body>
<script>
$.ajax({
url:'http://test.com/abc.php?name=hh&age=21',
type:'get',
dataType:'jsonp',
jsonp:"back",//jsonp默认参数是callback这个参数会追加到url上面并且jquery会自动赋值,后端去接受
success:function(data,status,xhr){
alert('姓名'+data.name+'年龄'+data.age);
}
})
</script>
</body>
</html>

 

PHP代码(test.com本地配置虚拟域名即可)

test.com/abc.php

<?php
$data['name'] = $_GET['name'];
$data['age'] = $_GET['age'];
echo $_GET['back']."(".json_encode($data).")";
?>

 //第二种方法,原理就是请求雅虎的服务器去请求别的服务器

jQuery(document).ready(function() {
        //从外网获取Json数据
    $.getJSON(
        "http://query.yahooapis.com/v1/public/yql", 
        {   
            q: "select * from json where url='http://你的接口地址'",  
            format: "json"   
        }, 
        function(data) {   
        console.log(data.results);   
    }); 
}); 

 

posted @ 2017-07-09 00:44  王召波  阅读(206)  评论(0编辑  收藏  举报