2.下面使用JSONP亭饵,將前端代碼中的ajax請求去掉梁厉,添加了一個script標(biāo)簽,標(biāo)簽的src指向了另一個域www.practice-zhao.com下的remote.js腳本
<!DOCTYPE html>
<html>
<head>
? ? <title>GoJSONP</title>
</head>
<body>
<script type="text/javascript">
? ? function jsonhandle(data){
? ? ? ? alert("age:" + data.age + "name:" + data.name);
? ? }
</script>
<script type="text/javascript" src="jquery-1.8.3.min.js">
</script>
<script type="text/javascript" src="http://www.practice-zhao.com/remote.js"></script>
</body>
</html>
----------------------------------------------
3.將前端代碼再進(jìn)行修改八秃,代碼如下:
<!DOCTYPE html>
<html>
<head>
? ? <title>GoJSONP</title>
</head>
<body>
<script type="text/javascript">
? ? function jsonhandle(data){
? ? ? ? alert("age:" + data.age + "name:" + data.name);
? ? }
</script>
<script type="text/javascript" src="jquery-1.8.3.min.js">
</script>
<script type="text/javascript">
? ? $(document).ready(function(){
? ? ? ? var url = "http://www.practice-zhao.com/student.php?id=1&callback=jsonhandle";
? ? ? ? var obj = $('<script><\/script>');
? ? ? ? obj.attr("src",url);
? ? ? ? $("body").append(obj);
? ? });
</script>
</body>
</html>
---------------------
這里動態(tài)的添加了一個script標(biāo)簽计技,src指向跨域的一個php腳本垮媒,并且將上面的js函數(shù)名作為callback參數(shù)傳入,那么我們看下PHP代碼怎么寫的:
<?php
$data = array(
? ? 'age' => 20,
? ? 'name' => '張三',
);
$callback = $_GET['callback'];
echo $callback."(".json_encode($data).")";
return;
PHP代碼返回了一段JS語句萌衬,即
jsonhandle({
? ? "age" : 15,
? ? "name": "張三",
})
---------------------
4.最后jQuery提供了方便使用JSONP的方式它抱,代碼如下:
<!DOCTYPE html>
<html>
<head>
? ? <title>GoJSONP</title>
</head>
<body>
<script type="text/javascript" src="jquery-1.8.3.min.js">
</script>
<script type="text/javascript">
? ? $(document).ready(function(){
? ? ? ? $.ajax({
? ? ? ? ? ? type : "get",
? ? ? ? ? ? async: false,
? ? ? ? ? ? url : "http://www.practice-zhao.com/student.php?id=1",
? ? ? ? ? ? dataType: "jsonp",
? ? ? ? ? ? jsonp:"callback", //請求php的參數(shù)名
? ? ? ? ? ? jsonpCallback: "jsonhandle",//要執(zhí)行的回調(diào)函數(shù)
? ? ? ? ? ? success : function(data) {
? ? ? ? ? ? ? ? alert("age:" + data.age + "name:" + data.name);
? ? ? ? ? ? }
? ? ? ? });
? ? });
</script>
</body>
</html>
---------------------
作者:云中的魚
來源:CSDN
原文:https://blog.csdn.net/u011897301/article/details/52679486
版權(quán)聲明:本文為博主原創(chuàng)文章混移,轉(zhuǎn)載請附上博文鏈接歌径!