深圳全飞鸿

标题: jsonp服务端代码 [打印本页]

作者: zhgc    时间: 2020-8-19 22:36
标题: jsonp服务端代码



  1. $callback = $_REQUEST['callback'];

  2. // Create the output object.
  3. $output = array('a' => 'Apple', 'b' => 'Banana');

  4. //start output
  5. if ($callback) {
  6.     header('Content-Type: text/javascript');
  7.     echo $callback . '(' . json_encode($output) . ');';
  8. } else {
  9.     header('Content-Type: application/x-json');
复制代码

作者: zhgc    时间: 2020-8-19 23:51
jsonp本地代码


  1. <script>
  2. $(function(){
  3.   getData();
  4.   setInterval(function(){
  5. var head = document.head || $('head')[0];
  6. var script = $(head).find('script')[0];
  7. if (script){
  8.         var src = script.src || '';
  9.         var idx = src.indexOf('callback=');
  10.         if(idx != -1){
  11.                 var idx2 = src.indexOf('&');
  12.                 if (idx2 == -1){idx2 = src.length;}
  13.                 var jsonCallback = src.substring(idx + 9, idx2);
  14.                 delete window[jsonCallback];
  15.                 if (script.parentNode){
  16.                         script.parentNode.removeChild(script);
  17.                 }
  18.         }
  19. }
  20. getData();
  21.   }, 1000);
  22. });
  23. function getData(){
  24.     jQuery.ajax({  
  25.         //src="http://127.0.0.1:808/hello1.html?callback=zz&_=1597846439408"
  26.         //src="http://127.0.0.1:808/hello1.html?callback=jQuery17206514656749972916_1597846503900&_=1597846534352
  27.                 url:"http://127.0.0.1:808/hello1.html?BB=17",
  28.                 type:"GET",  
  29.                 dataType:"jsonp",
  30.                                 //jsonp: "callback",
  31.                                 //jsonpCallback:"zz",
  32.                 success:function(result){
  33.                            alert(result);
  34.                         } ,
  35.                                 error:function(xOptions, textStatus){console.log(textStatus);}
  36.                                 })                       
  37. };
  38. </script>
复制代码

作者: zhgc    时间: 2023-8-21 19:54
本帖最后由 zhgc 于 2023-8-21 20:07 编辑

JSONP调用中,   jsonp和jsonpCallback 属性是什么用

[backcolor=rgba(255, 255, 255, 0.86)]在 JSONP 中,jsonp 是回掉函数名的参数名,默认为 callback,服务端通过它来获取到回掉函数名。而 jsonpCallback 则是回掉函数名,默认由 jQuery 自动生成 。

src="http://127.0.0.1:808/hello1.html?callback=jQuery17206514656749972916_1597846503900&_=1597846534352

那jsonp: "callback",
服务器通过josnp属性得到参数名是callback, 然后通过callback名得到jQuery17206514656749972916_1597846503900&_=1597846534352





欢迎光临 深圳全飞鸿 (http://www.nagomes.com/disc/) Powered by Discuz! X3.2