web三種跨域請求資料方法

來源:互聯網
上載者:User

標籤:

web三種跨域請求資料方法
以下測試代碼使用php,瀏覽器測試使用IE9,chrome,firefox,safari<!DOCTYPE HTML><html><head>    <meta charset="UTF-8">    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"></script>    <script type="text/javascript" id="loadjson"></script>    <script type="text/javascript">    // 第一種    // test1.php在伺服器設定請允許跨域(注意:IE9測試不通過)    $.ajax({           type: ‘POST‘,           url: ‘http://127.0.0.1:8081/test/test1.php‘,           data: ‘name=penngo‘,           dataType: ‘json‘,           success: function(msg){              $(‘#json‘).html(JSON.stringify(msg));           }        });     // 第二種    // test2.php使用jsonp    $.ajax({           type: ‘GET‘,           url: ‘http://127.0.0.1:8081/test/test2.php?callback=?‘,           data: ‘name=penngo‘,           dataType: ‘jsonp‘,           success: function(msg){              $(‘#jsonp‘).html(JSON.stringify(msg));           }        });     // 使用js標籤載入方式,該方式為非同步,通過testjs()回調    var testjs = function(msg){         $(‘#js‘).html(JSON.stringify(msg));    }    $(‘#loadjson‘)[0].src = ‘http://127.0.0.1:8081/test/test3.php?method=testjs&name=penngo‘;    </script> </head><body>    header跨域:    <div id="json">            </div>    <br/>    jsonp跨域:    <div id="jsonp">            </div>    <br/>    js請求實現跨域:    <div id="js">            </div></body></html> 伺服器端處理test1.php<?php    header("Access-Control-Allow-Origin: *");    $name = $_REQUEST[‘name‘];    $result = array(‘success‘=>1, ‘name‘=>$name);    echo json_encode($result);?> test2.php<?php    $callback = $_REQUEST[‘callback‘];    $name = $_REQUEST[‘name‘];    $result = array(‘success‘=>1, ‘name‘=>$name);    $jsonData = json_encode($result);    echo $callback . "(" . $jsonData . ")";?> test3.php<?php    $method = $_REQUEST[‘method‘];    $name = $_REQUEST[‘name‘];    $result = array(‘success‘=>1, ‘name‘=>$name);    $jsonData = json_encode($result);    echo "$method($jsonData);";?> IE9測試,頁面輸出內容header跨域: jsonp跨域: {"success":1,"name":"penngo"}js請求實現跨域: {"success":1,"name":"penngo"}chrome,firefox,safari測試,頁面輸出內容header跨域:{"success":1,"name":"penngo"}jsonp跨域:{"success":1,"name":"penngo"}js請求實現跨域:{"success":1,"name":"penngo"}  

web三種跨域請求資料方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.