扫码关注官方订阅号
想知道有没有什么前端的方法可以解决js的跨域请求问题,网上找了一些方法,有说可以使用
jsonp - 对方服务器支持
自己搭个服务器做中转 - 分两次操作
Access-Control-Allow-Origin - 也要对方服务器支持
所以如果服务器不是自己搭建或者无法做改动,请用第二种
用FlyJSONP应用JSONP实现
服务器代码
<?php namespace Home\Controller; use Think\Controller; class IndexController extends Controller { public $callback; public $model; public function __construct() { parent::__construct(); $this->callback = I('callback'); if(!$this->callback) $this->error('系统出错,请稍后再试'); $this->model = D('Posts'); } public function man(){ $page = I('page',0,'intval'); $where = array(); $where['post_status']='publish'; $where['ping_status']='open'; $where['post_password'] = ''; $where['post_type'] = 'post'; $where['post_date'] = array('lt',date('Y-m-d H:i:s')); $row_num = C('row_num'); $field = 'a.ID,a.post_date,a.comment_count,a.post_title,a.post_excerpt,b.display_name'; $data=$this->model->alias('a')->join('__USERS__ as b on a.post_author=b.ID')->field($field)->where($where)->order('post_date desc')->limit($page*$row_num ,$row_num )->select(); $this->jsonp($data); } public function post(){ $where = array(); $where['post_status']='publish'; $where['ping_status']='open'; $where['post_password'] = ''; $where['post_type'] = 'post'; $where['post_date'] = array('lt',date('Y-m-d H:i:s')); $id = I('id'); $where['ID'] = $id; $data=$this->model->where($where)->field('post_title,post_content')->find(); $data['post_content'] = wpautop($data['post_content']); $this->jsonp($data); } private function jsonp($data){ echo $this->callback.'('.json_encode($data).')'; die; } }
客户端请求
/** * jsonp请求 * @param url * @param post_data */ function ajax(url){ var postdata = arguments[1] ? arguments[1] : null; var success = arguments[2] ? arguments[2] : null; var error = arguments[3] ? arguments[3] : null; $.ajax({ type: "post", async: false, data:postdata, url: url, dataType: "jsonp", jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback) jsonpCallback:"callback",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据 success: function(data){ (success && typeof (success) == "function") && success(data); }, error: function(){ if(!error)msg('数据加载失败'); (error && typeof (error) == "function") && error(data); } }); } ajax(root+"/Index/man",null,function(data){ //var tmp = template(tpl.get('list'),{data:data}); var tmp = template(tpl.get('list'),{data:data}); $(this.el).html(tmp); console.log(t); return t; });
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
jsonp - 对方服务器支持
自己搭个服务器做中转 - 分两次操作
Access-Control-Allow-Origin - 也要对方服务器支持
所以如果服务器不是自己搭建或者无法做改动,请用第二种
用FlyJSONP应用JSONP实现
服务器代码
客户端请求