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返回的是一段字符串,這段字符串是函數執行的字符串形式

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM