php+ajax简单实现跨域(http+https)请求调用
生活随笔
收集整理的這篇文章主要介紹了
php+ajax简单实现跨域(http+https)请求调用
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
當(dāng)一個網(wǎng)站 a站 需要調(diào)用另一個網(wǎng)站 b站 列表文章時
比如:www.a123.com 調(diào)用 www.b456.com 文章
在 a站 建立php文件獲取 b站 資源文章到本地后,再傳遞a站前端
在網(wǎng)站 b456 下的文件為
<ul class="ls_wz"> <li><a href="#" target="_blank" title="title1" >內(nèi)容1</a><span>[1970-01-01]</span></li> <li><a href="#" target="_blank" title="title2" >內(nèi)容2</a><span>[1970-01-01]</span></li> <li><a href="#" target="_blank" title="title3" >內(nèi)容3</a><span>[1970-01-01]</span></li> </ul>在網(wǎng)站 a123 根目錄(隨意)下建立
a .php 文件:
<?php //獲取文中傳遞參數(shù) //$data['title']=$_GET['title']; // $data['link']=$_GET['link']; // $data['pubDate']=$_GET['pubDate'];$data['callback']=$_GET['callback'];//尤為重要模擬跨callback//$data = array('title'=>title,'link'=>link,'pubData'=>pubData,'callback'=>callback);//$dataToJson = json_encode($data);//var_dump($data);$url="http://www.b456.com/b.php";//B站請求地址$postdata = http_build_query($data);$opts = array('http'=>array('method'=>"GET",'timeout'=>60,));$context = stream_context_create($opts);$result = file_get_contents($url."?".$postdata, false, $context);echo $result;//var_dump($result);?>a.html 文件:
<script type="text/javascript" src="js/jquery.min.js"></script> <div id="zd" class="ls_wz" style="height:144px; overflow:hidden"> </div> <script>$(function() {var url = 'http://www.a123.com/a.php';$.ajax({type: "get",url: url,async: false,//dataType:'jsonp', success: function (data) {var html = data;//html += '<p class="more"><a target="_blank" href="#">更多+</a></p>'; $("#zd").html(html);//alert('#zd'); }})})</script>CSS:
/*css*/ .ls_wz{ float: left;height:144px;overflow:hidden;} .ls_wz li{ list-style:none; line-height:23px; padding: 0 8px; font-size:12px; width:320px; padding-left:12px;overflow:hidden;white-space: nowrap;text-overflow: ellipsis;} .ls_wz li a {word-break: keep-all;white-space: nowrap;display: inline-block;width: 320px;overflow: hidden;text-decoration:none;text-overflow: ellipsis;} .ls_wz li a:hover{color:#C30000; text-decoration:underline; } .ls_wz li span{ display:none;}還有一種情況就是,當(dāng)遇到
http 和 https 通過認(rèn)證驗(yàn)證的跨域請求調(diào)用:
header('Content-Type: text/html;charset=utf-8'); header('Access-Control-Allow-Origin: *'); //指定訪問網(wǎng)站請求 header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允許請求的類型 header('Access-Control-Allow-Credentials: true'); // 設(shè)置是否允許發(fā)送 cookies header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin'); // 設(shè)置允許自定義請求頭的字段當(dāng)然了,不希望別人訪問當(dāng)前的文件:
//禁止訪問當(dāng)前文件 $fromurl="http://localhost/"; //跳轉(zhuǎn)到這個地址。 if( $_SERVER['HTTP_REFERER'] == "" ) { header("Location:".$fromurl); exit; }轉(zhuǎn)載于:https://www.cnblogs.com/chervehong/p/10294367.html
總結(jié)
以上是生活随笔為你收集整理的php+ajax简单实现跨域(http+https)请求调用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: nginx日志自动切割
- 下一篇: BZOJ 1084: [SCOI2005