Native js simple JSONP

Original link: https://www.mk2048.com/blog/blog.php?id=h02bb1hchjkj&title=%E5%8E%9F%E7%94%9Fjs%E5%AE%9E%E7%8E%B0%E7% AE% 80% E5% 8D% 95JSONP

JSONP is a very common method to achieve cross-domain requests. The basic idea is to use the browser requests the JS file may be cross-domain outside the chain, use of this feature for data transmission.

JS achieve with native JSONP very simple, nothing more than that:

1) Define a function for cross-domain processing of the received data.

2) generating a dom node (script node), then charged to the above object of the src attribute and the URL transmission parameters.

3) In the inter-server receives the GET request that returns the data (character string defined function call before returning).

4) script generated by the node before deleting.

Presentation as follows:

1) First, a need that is homologous to the server, a cross-domain access.

The easiest way is to use two virtual hosts apache configuration.

//浏览器器端
<script type="text/javascript">
    //定义一个发送Jsonp请求的函数
    function jsonp(obj) {
        //定义一个处理Jsonp返回数据的回调函数
	window["callback"] = function(object) {
            obj.success(JSON.parse(object));
        }
        var script = document.createElement("script");
        //组合请求URL
        script.src = obj.url   "?fn=callback";
        for(key in obj.data){
            script.src  ="&"   key   "="   obj.data[key];
        }
        //将创建的新节点添加到BOM树上
        document.getElementsByTagName("body")[0].appendChild(script);	
    }
</script>

<script type="text/javascript">
    //调用Jsonp函数发送jsonp请求
    jsonp({
        url:"http://localhost/index.php",
        data:{
            name:"小明",
        },
        success:function(obj) {
            alert("性别"   obj.sex);
        }
    });
</script>

  

 

//服务器端
<?php
header('Content-Type: application/json; charset=UTF-8');

$fn = $_GET["fn"];

$name = $_GET["name"];
$result = array();
if($name == "小明"){
$result["sex"] = "男";
} else if($name == "小红"){
$result["sex"] = "女";
}else {
$result["sex"] = "未知";
}

echo $fn . "('" . json_encode($result) ."')";

  

 


More professional front-end knowledge, make the [2048] ape www.mk2048.com

Guess you like

Origin blog.csdn.net/weixin_39037804/article/details/102757156