html代碼
- <html>
- <head>
- <meta http-equiv="content-type" content="text/html;charset=utf-8">
- <title>jsonp跨域技術</title>
- <style type="text/css">
- #h1{
- text-align:center;
- }
- #div{
- margin:0 auto;
- width:300px;
- height:200px;
- background:#ccc;
- }
- button{
- display:block;
- margin:0 auto;
- }
- </style>
- </head>
- <body>
- <h1 id='h1'>jsonp跨域技術</h1>
- <div id='div'>
- </div>
- <h1 id='h1'><script>document.write(new Date())</script></h1>
- <button id="bid" name="button" onclick="fun()">jsonp請求數據</button>
- </body>
- <script>
- //實現js與php發生數據交互的一種技術,js通過請求php腳本,然後得到響應數據,最核心的作用是實現js跨域,跨域就是跨主機或者跨服務器
- //爲什麼要用jsonp技術,是因爲ajax技術無法跨域
- function fasong3(data){
- //alert(data.name);//彈出
- //alert(data.age);
- var str="";
- str+="name:"+data.name+"<br>";
- str+="age:"+data.age+"<br>";
- document.getElementById('div').innerHTML=str;
- }
- function fun(){
- var obj=document.createElement("script");//創建標籤
- obj.src="http://192.168.11.188/index111.php?cb=fasong3";//請求地址
- document.body.appendChild(obj);//綁定子類
- }
- </script>
- </html>
http://192.168.11.188/服務器地址代碼
- <?php
- $fasong3 = $_GET["cb"];
- //echo "<script>$fasong3('1111111')</script>";
- $str='{"name":"nihao","age":"30"}';
- echo $fasong3.'('.$str.')';