jsonp的实现

jsonp实现

客户端

index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jsonp测试</title>
</head>
<body id="body">
<script>
    function get() {
        alert('开始调用');
        var theJ = document.createElement('script');
        theJ.setAttribute('src', 'http://tp5/index/index/index/?f=jsonP&name=jijuxie');
        var body = document.querySelector('#body');
        body.appendChild(theJ);
    }
    setTimeout(function () {
        get();
    }, 1000);
</script>
</body>
</html>

服务端

这里使用的是tp5框架

tp5/application/index/controller/index.php
<?php
namespace app\index\controller;

use think\Request;

class Index
{
    public function index()
    {
        $request = Request::instance();
        $theF = $request->param('f');//读取get参数
        $theName = $request->param('name');
        if ($request->isGet()&&!empty($theF)) {
            $return = ['code' => 0, 'message' => 'jsonp通信成功', 'data' => ['name' => $theName]];
            $return = $theF . "(" . json_encode($return) . ")";//拼接字符串成执行方法的样子
        } else {
            //这个地方可以返回一般json的模式,使这个接口通用jsonp和ajax和一般接口
//            $return = ['code' => 0, 'message' => 'ajax/api通信成功',  'data' => ['name' => $theName]];
            $return = ['code' => 1, 'message' => '使用了非jsonP', 'data' => []];
        }
        header('Content-Type: application/json; charset=utf-8');
        return $return;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值