实现jsonp的方式如下:
//客户端,jquery <!DOCTYPE html> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script> //第1种 <script type="text/javascript"> $.getJSON("http://laravel.local/test/jsonp?callback=?", {name: encodeURIComponent('tester')}, function (result) { console.log(result); }); //第2种 $.ajax({ url: "http://laravel.local/test/jsonp", dataType: 'jsonp', data: {name: encodeURIComponent('tester')}, jsonp: 'callback', success: function (result) { console.log(result); }, timeout: 3000 }); //第3种 $.get('http://laravel.local/test/jsonp?callback=?', {name: encodeURIComponent('tester')}, function (result) { console.log(result); }, 'jsonp'); </script> </head>
服务器端
//服务端,php laravel框架 <?php namespace app\Http\Controllers; use Illuminate\Http\Request; class TestController extends Controller { public function getIndex(Request $request) { $name=$request->input('name'); $arr=array('a'=>$name,'b'=>2,'c'=>3,'d'=>4,'e'=>5); $callback=$request->input('callback'); return $callback.'('.json_encode($arr, JSON_UNESCAPED_UNICODE).')'; // return 'try{'.$callback.'('.json_encode($arr, JSON_UNESCAPED_UNICODE).')}catch(e){}'; } }