说实话,我学了这么久,其实也没有好好了解这个东西,固然日常本身在前端方面也涉猎较浅。php
JSONP(JSON with Padding)是JSON的一种“使用模式”,可用于解决主流浏览器的 跨域 数据访问的问题。
跨域? 因为同源策略的缘由,也就是说你请求资源时,浏览器对于不是你当前域名或者端口号都相同的地址给与禁止访问,不容许你获取资源html
同源策略:前端
浏览器中对<script>、<img>、<iframe> 是给予支持的,因此咱们能够采用相似引用数据的方式来获取资源
处理流程:ajax
// JS <button class="getRequest">发起跨域请求</button> <textarea name="" id="" cols="30" rows="10" disabled></textarea> <script> function showdata(result) { console.log(result); } $('.getRequest').on('click', function(){ //1) // $('head').append("<script src='http://localhost/jsonp/service.php?jsonp=showdata'><\/script>"); //2) $.ajax({ url : 'http://localhost/jsonp/service.php', type: 'GET', dataType: 'jsonp', jsonp: 'jsonp', // 自定义,保证后端能经过这个key值获取函数名 jsonpCallback: "showdata",//自定义的jsonp回调函数名称 success: function (json) { alert('success'); }, error: function () { alert('fail'); } }) }) </script> -------------------- header('Content-type: application/json'); //获取回调函数名 $jsonp = htmlspecialchars($_REQUEST ['jsonp']); //json数据 $json_data = '["customername1","customername2"]'; //输出jsonp格式的数据 echo $jsonp . "(" . $json_data . ")"; // 格式进行拼接,获得showdata(["customername1","customername2"]); --------------
因而可知,其实就是远程服务器代前端处理了相关函数,经过返回一个带参数的函数表达式,来进行执行相关逻辑代码。 有效避免了直接向远程服务器请求数据