ajax获取不同域的数据,只要协议,域名,端口有任何不同,都会被当作是不同的域。
1.jsonp解决跨域问题是一种非官方得方式,这种方式只支持get方式,不如post安全,即使jquery得jsonp方法,type设置为post,也会自动变成get。该协议的一个要点就是允许用户传递一个callback参数给服务端,然后服务端返回数据时会将这个callback参数作为函数名来包裹住JSON数据
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>jquery </title><script type="text/javascript" src="scripts/jquery-3.2.1.js"></script><script type="text/javascript">$.ajax({ ????type: "get", ????data: "random="+Math.random(), ????url: "jsonp.php", ????dataType: "jsonp", ????jsonp: "callback", ????success: function(data) { ??????console.log(data); ????}, ????error: function() { ??????console.log(‘Request Error.‘); ????} });</script></head><body> ?</body></html>
<?php$data = array( ????‘rand‘ => $_GET[‘random‘], ????‘msg‘ => ‘Success‘, ???‘callback‘ => $_GET[‘callback‘], ?); echo $_GET[‘callback‘].‘(‘.json_encode($data).‘)‘;
2.Ajax跨域请求:CORS
CORS,又称跨域资源共享,英文全称Cross-Origin Resource Sharing。假设我们想使用Ajax从a.com的页面上向b.com的页面上要点数据,通常情况由于同源策略,这种请求是不允许的,浏览器也会返回“源不匹配”的错误,所以就有了“跨域”这个说法。但是我们也有解决办法,我们可以再b.com的页面header信息中增加一行代码:
header("Access-Control-Allow-Origin:*");
也可以改为允许得域名例如:
header(‘Access-Control-Allow-Origin:http://www.baidu.com‘);
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>jquery </title><script type="text/javascript" src="scripts/jquery-3.2.1.js"></script><script type="text/javascript">$.ajax({ ????type: "get", ????data: "random="+Math.random(), ????url: "cors.php", ????dataType: "json", ????success: function(data) { ????????console.log(data); ????}, ????error: function() { ????????console.log(‘Request Error.‘); ????} });</script></head><body></body></html>
<?phpheader(‘Access-Control-Allow-Origin:*‘); $data = array( ????‘rand‘ => $_GET[‘random‘], ????‘msg‘ => ‘Success‘ ); echo json_encode($data); ?
header(‘content-type:application:json;charset=utf8‘); ?header(‘Access-Control-Allow-Origin:*‘); ?header(‘Access-Control-Allow-Methods:POST‘); ?header(‘Access-Control-Allow-Headers:x-requested-with,content-type‘); ?
3.判断是否是ajax请求
function isAjax() { ????return @$_SERVER[‘HTTP_X_REQUESTED_WITH‘] == ‘XMLHttpRequest‘ ? true : false; }
ajax跨域问题
原文地址:https://www.cnblogs.com/mengor/p/7999651.html