1.jsonp是为了解决跨域问题

2.jsonp是get请求

jsonp原理:动态的插入script标签,通过script标签get请求成功后执行我们请求到的js代码(也就是会执行我们在url中callback指定的函数),而函数传入的参数就是客户端所需要的数据。代码如下:

客户端:

<script>

创建并且插入script标签

 function createscript(reqUrl){

  var Ocreatescript = document.createElement('script');

  Ocreatescript .type = 'text/javascript';

  Ocreatescript.src = reqUrl;

  document.getElementsByTagName('head')[0].appendChild(Ocreatescript);

}

创建一个hello方法

function hello(res){

  console.log(res);

}

 createscript('http://loveme.com/index.php?callback=hello ');

请求回来的内容:

hello({ 'hi': 'nihao' }); //调用了上面的hello方法

 </script>

 

服务端:index.php

<?php

$a=$_GET["callback"];

echo $a.'({ 'hi': 'nihao' })'

?>

posted on 2018-01-14 23:23  木子月  阅读(142)  评论(0编辑  收藏  举报