在桌面上工作时,最简单的调用JSONP数据的技术在移动浏览器上不起作用。虽然setTimeout()
对CORS来说有点不好,但事实并非如此。
function thumb_handler(data){
$('.js-itm-hover-img-front[data-id=' + data.id + ']').attr('src', data.img_front).addClass('m');
$('.js-itm-hover-img-back[data-id=' + data.id + ']').attr('src', data.img_back).addClass('m');
}
$('.prod-img-wrap').each(function(ind) {
let imgs_scope = {},
front = $(this).find('.js-itm-hover-img-front'),
back = $(this).find('.js-itm-hover-img-back'),
img_front = front.attr('data-img'),
img_back = back.attr('data-img'),
id = front.attr('data-id');
imgs_scope[id] = {
'img_front': img_front,
'img_back' : img_back ? img_back : '',
};
function requestServerCall() {
var head = document.head;
var script = document.createElement('script');
script.setAttribute('src', 'index.php?route=product/category/product_thumb_work&callback=thumb_handler&id=' + id + '&img_front=' + img_front + '&img_back=' + img_back);
head.appendChild(script);
head.removeChild(script);
}
// setTimeout(function(){
requestServerCall();
// }, ind * 300);
});
服务器端相关方法如下。我的猜测很可能是设置正确的标题。
public function product_thumb_work() {
$this->load->model('tool/image');
$this->load->model('catalog/product');
$json = array();
if (isset($this->request->get['id'])) {
// foreach($this->request->get['ids_imgs'] as $id => $imgres) {
$json['id'] = $this->request->get['id'] ? $this->request->get['id'] : '';
$img_front = $this->model_tool_image->resize($this->request->get['img_front'], $this->config->get($this->config->get('config_theme') . '_image_product_width'), $this->config->get($this->config->get('config_theme') . '_image_product_height'));
$json['img_front'] = $img_front ? $img_front : '';
$img_back = $this->model_tool_image->resize($this->request->get['img_back'], $this->config->get($this->config->get('config_theme') . '_image_product_width'), $this->config->get($this->config->get('config_theme') . '_image_product_height'));
$json['img_back'] = $img_back ? $img_back : '';
// }
}
// $this->response->setOutput(json_encode($json));
$callback = $this->request->get['callback'];
// $message = $this->request->get['message'].' you got a response from server yipeee!!!';
$jsonResponse = '{"id":"' . $json['id'] . '", "img_front":"' . $json['img_front'] . '", "img_back":"' . $json['img_back'] . '"}';
// if (isset($this->request->server['HTTP_ORIGIN'])) {
// $this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
$this->response->addHeader('Access-Control-Allow-Origin: *');
$this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
$this->response->addHeader('Access-Control-Max-Age: 1000');
$this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
$this->response->addHeader('Content-Type: application/javascript');
// }
echo $callback . '(' . $jsonResponse . ')';
}
我做错了什么?请帮忙。