script的src属性能实现跨越访问

urlencode.php

<?php
    $name=$_POST['name'];
    $age = $_POST['age'];
    $array = array("name"=>$name,"age"=>$age);
    $result = json_encode($array);
    echo ($result);
?>

demo.html

<!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>
    <script>
       var xhr = new window.XMLHttpRequest();
       xhr.onreadystatechange = function(){
           if(xhr.status == 200 && xhr.readyState == 4){
               var result = xhr.responseText;
               result = JSON.parse(result);
               console.log(result);
           }
       } 
       xhr.open("post","./php/urlencode.php",true);
       xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
       xhr.send("name=pmx&age=20");
    </script>
</body>
</html>

结果

通常我们使用XMLHttpRequest请求php获取数据。但是请求的对象仅限于相同域内,对于不同域的请求,我们得使用jsonp技术

 

jsonp.php

<?php
    $func = $_GET['jsonc'];
    $json_data = "'pan',30";
    echo $func."(".$json_data.")";
?>

 

demo.html

<!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>
    <script>
        function callback_pmx(name,age) {
            console.log(name,age);
        }
    </script>

    <script src="./php/jsonp.php?jsonc=callback_pmx"></script>
</head>

<body>

</body>

</html>

结果:

1.在script中以get请求php文件,jsonp.php通过$_GET对象获得了传给php的参数callback_pmx,这个参数值是一段字符串,和js中预定义好的函数同名。

2.php返回函数执行的字符串表现形式,js得到后,执行这段函数

jsonp.php返回的是一段字符串,这段字符串是函数执行的字符串形式

 

转载于:https://www.cnblogs.com/bibiafa/p/9367184.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值