• 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返回的是一段字符串,这段字符串是函数执行的字符串形式

  • 相关阅读:
    linux下配置redis
    前端之JavaScript:JS之DOM对象一
    前端之JavaScript:JavaScript对象
    css样式之补充
    css属性中常见的操作方法
    css属性操作
    css选择器
    html 表单操作
    前端基础之html
    1231211221211221
  • 原文地址:https://www.cnblogs.com/bibiafa/p/9367184.html
Copyright © 2020-2023  润新知