关于跨域问题的解决方法:https://segmentfault.com/a/1190000000718840
什么是ajax跨域问题:
比如:在www.microblog.com域名下想访问test.elf.com这个域名的某个接口,用ajax调用的时候会失败。
解决方法:
但是,如果在www.microblog.com的html里面嵌入类似
(<script type="text/javascript" src="http://test.elf.com/jsonp.php?callback=jsonp_callback"></script>
或者<img src="http://test.elf.com/jsonp.js">)这样的代码却能访问。
so借用这种思路(可以跨域名引用文件的思路)
解决方案一:
在www.microblog.com里面嵌入如下js:
<!DOCTYPE html>
<html>
<head>
<title>jsonp test</title>
</head>
<body>
<script type="text/javascript">
function jsonp_callback(data){
alert(data);
}
</script>
<script type="text/javascript" src="http://test.elf.com/jsonp.php?callback=jsonp_callback"></script>
</body>
</html>
在test.elf.com被调用的接口jsonp.php文件里面:
<?php $callback = $_GET['callback']; $data = array('aaa'); echo $callback.'('.json_encode($data).')';
这样就能实现跨域名ajax调用了。
解决方案二(JQ版本):
<!DOCTYPE html> <html> <head> <title>jsonp test</title> <script type="text/javascript" src="./public/home/js/jquery-1.7.2.min.js"></script> </head> <body> <script type="text/javascript"> function getName(data){ alert(data); } </script> <script type="text/javascript"> var jsonp_url = "http://test.elf.com/jsonp.php"; $.ajax({ url : jsonp_url, type: 'get', dataType: 'jsonp', jsonp: 'callback', jsonpCallback:'getName', // success: function(json){ // alert(json); // } }) </script> </body> </html>
server:
<?php $callback = $_GET['callback']; $data = array('aaa', 'bbb'); echo $callback.'('.json_encode($data).')';