使用JSON實現資料的跨域傳輸的php代碼_php技巧

來源:互聯網
上載者:User
後台profile.php代碼:
複製代碼 代碼如下:

<?php
$arr = array(
'firstname' => iconv('gb2312', 'utf-8', '非誠'),
'lastname' => iconv('gb2312', 'utf-8', '勿擾'),
'contact' => array(
'email' =>'fcwr@jb51.net',
'website' =>'http://www.jb51.net',
)
);
//將一個數組JSON
$json_string = json_encode($arr);
//此處注意,雙引號能對裡面的變數當變數進行處理,單引號則不會
echo "getProfile($json_string)";
?>

需要指出的是,在非UTF-8編碼下,中文字元將不可被encode,結果會出來空值,所以,如果你使用 gb2312編寫PHP代碼,那麼就需要將包含中文的內容使用iconv或者mb轉為UTF-8再進行json_encode。
前台index.html代碼:
複製代碼 代碼如下:

<script type="text/javascript">
function getProfile(str) {
var arr = str;
document.getElementById("firstname").innerHTML = arr.firstname;
}
</script>
<body>
<div id="firstname"></div>
</body>
<!-- 使用JSON實現跨域的資料調用,此處如將“profile.php”改為“http://另外一個網域名稱/profile.php”就更能看出跨域了-->
<script type="text/javascript" src="profile.php"></script>

將JSON格式的資料直接賦值給javascript中的變數,就變成數組了,接下來操作起來就會非常的方便,此處如果使用XML做為資料轉送,後續操作就不方便嘍。
很顯然,當index.html調用profile.php時,JSON字串產生,並作為參數傳入getProfile,然後將暱稱插入到div 中,這樣一次跨域資料互動就完成了
調用index.html
輸出:非誠

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.