解决ajax跨域问题的多种方法

前端之家收集整理的这篇文章主要介绍了解决ajax跨域问题的多种方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

解决ajax跨域问题的多种方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//第一种方法使用jsonp的方式<br><br><script type="text/javascript" src="http://www.youxiaju.com/js/jquery-1.4.2.min.js"></script>
<script type= "text/javascript" >
$( function (){
$.ajax(
{
type: 'get' ,
url : 'http://www.youxiaju.com/validate.PHP?loginuser=lee&loginpass=123456' PHP plain" style="margin:0px!important; padding:0px!important; border:0px!important; bottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.8em!important; outline:0px!important; overflow:visible!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,
dataType : 'jsonp' PHP plain" style="margin:0px!important; padding:0px!important; border:0px!important; bottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.8em!important; outline:0px!important; overflow:visible!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,
jsonp: "jsoncallback" PHP plain" style="margin:0px!important; padding:0px!important; border:0px!important; bottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.8em!important; outline:0px!important; overflow:visible!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,
@H_301_111@ success : (data) {
alert( "用户名:" + data.user + " 密码:" + data.pass);
},
error : () {
'fail' );
}
}
);
})
</script>

  

<?PHP
header('Content-Type:text/html;Charset=utf-8');
$arr = array(
    "user" => $_GET['loginuser'],"pass" => $_GET['loginpass'],"name" => 'response'

);
echo $_GET['jsoncallback'] . "(".json_encode($arr).")";

  第二种方式增加headr头

 假设我们页面或者应用已在http://www.test1.com上了,而我们打算从http://www.test2.com请求提取数据。一般情况下,如果我们直接使用 AJAX 来请求将会失败,浏览器也会返回“源不匹配”的错误," 跨域"也就以此由来。
  利用 CORS,http://www.test2.com只需添加一个标头,就可以允许来自http://www.test1.com的请求,下图是我在PHP中的 hander() 设置, “*”号表示允许任何域向我们的服务端提交请求

  也可以设置指定的域名,如域名http://www.test2.com,那么就允许来自这个域名的请求

  当前我设置的header为“*”,任意一个请求过来之后服务端我们都可以进行处理&响应,那么在调试工具中可以看到其头信息设置,其中见红框中有一项信息是“ Access-Control-Allow-Origin:*”,表示我们已经启用CORS,如下图。
// 解决跨域请求
response.setHeader("Access-Control-Allow-Origin","*");// TODO 后续设置为项目域名
response.setHeader("Access-Control-Allow-Headers","*");// 设置跨域请求头
response.setHeader("Access-Control-Allow-Methods","*");// 设置 方法
  PS:由于demo都在我厂的两台测试机间完成,外网也不能访问,所以在这就不提供demo了,见谅
  简单的一个header设置,一个支持跨域&POST请求的server就完成了:)
  当然,如果没有开启CORS必定失败的啦,如下图:
  
原文链接:https://www.f2er.com/ajax/161067.html

猜你在找的Ajax相关文章