后臺(tái)profile.php代碼:
復(fù)制代碼代碼如下:
<?php
$arr = array(
'firstname' => iconv('gb2312', 'utf-8', '非誠'),
'lastname' => iconv('gb2312', 'utf-8', '勿擾'),
'contact' => array(
'email' =>'[email protected]',
'website' =>'//m.ythuaji.com.cn',
)
);
//將一個(gè)數(shù)組JSON
$json_string = json_encode($arr);
//此處注意,雙引號(hào)能對(duì)里面的變量當(dāng)變量進(jìn)行處理,單引號(hào)則不會(huì)
echo "getProfile($json_string)";
?>
需要指出的是,在非UTF-8編碼下,中文字符將不可被encode,結(jié)果會(huì)出來空值,所以,如果你使用 gb2312編寫PHP代碼,那么就需要將包含中文的內(nèi)容使用iconv或者mb轉(zhuǎn)為UTF-8再進(jìn)行json_encode。
前臺(tái)index.html代碼:
復(fù)制代碼代碼如下:
<script type="text/javascript">
function getProfile(str) {
var arr = str;
document.getElementById("firstname").innerHTML = arr.firstname;
}
</script>
<body>
<div id="firstname"></div>
</body>
<!-- 使用JSON實(shí)現(xiàn)跨域的數(shù)據(jù)調(diào)用,此處如將“profile.php”改為“http://另外一個(gè)域名/profile.php”就更能看出跨域了-->
<script type="text/javascript" src="profile.php"></script>
將JSON格式的數(shù)據(jù)直接賦值給javascript中的變量,就變成數(shù)組了,接下來操作起來就會(huì)非常的方便,此處如果使用XML做為數(shù)據(jù)傳輸,后續(xù)操作就不方便嘍。
很顯然,當(dāng)index.html調(diào)用profile.php時(shí),JSON字符串生成,并作為參數(shù)傳入getProfile,然后將昵稱插入到div 中,這樣一次跨域數(shù)據(jù)交互就完成了
調(diào)用index.html
輸出:非誠