<!DOCTYPE html>
<html lang="en">
<head>
? ? <meta charset="UTF-8">
? ? <meta name="viewport" content="width=device-width, initial-scale=1.0">
? ? <meta http-equiv="X-UA-Compatible" content="ie=edge">
? ? <title>Document</title>
</head>
<body>
? ? <h2>正則測試jsonp的封裝2</h2>
</body>
<script>
document.onclick = function(){
? ? var url="http://127.0.0.1/1907/jsonp/jsonp2.php";
? ? jsonp(url,function(res){
? ? ? ? console.log(res)
? ? },{
? ? ? ? user:"admin",
? ? ? ? pass:123,
? ? ? ? zx:"asd",? ? ? ? ? ? ? //后臺要執(zhí)行的函數(shù)名
? ? ? ? cloumnName:"zx"? ? ? ? //后臺接收的要執(zhí)行的函數(shù)名所在的字段名? ?
? ? })
}
function jsonp(url,success,data){
? ? //0.解析要發(fā)送的數(shù)據(jù)
? ? data = data || {};
? ? var str ="";
? ? for(var i in data){
? ? ? ? str += `${i}=${data[i]}&`
? ? }
? ? url = url + "?" + str;
? ? //1.創(chuàng)建script標簽,引入外部url
? ? var script = document.createElement("script");
? ? script.src = url;
? ? document.body.appendChild(script);
? ? //2.準備jsonp要執(zhí)行的函數(shù)
? ? window[data[data.columnName]]= function (res){
? ? ? ? success (res)
? ? }
}
</script>
</html>
PHP文件:
<?php
$a = @$_GET["user"];
$b = @$_GET["pass"];
$cb = @$_GET["zx"];
$data = "這是php通過jsonp接收到的跨域的的數(shù)據(jù),又還給你了:".$a."----".$b;
echo $cb."('".$data."')";
?>