跨域请求的3种方式

视频教程

跨域请求的方式:3种
1.后台代理
2.jsonp
3.HTML5中的XHR2
需要前端会的方法是后两种。
2.jsonp使用方法:只支持get方式
$.ajax({dataType:"jsonp",jsonp:"callback",success:...,error:...});//前台,修改数据类型,定义jsonp属性和参数名,等待后台调用
var request=$_GET("callback");//后台,接收前台定义好的参数名
var data=$jsonp.‘({"name:"jack",age:15})‘;//后台,使用jsonp处理数据,并返回前台
3.XHR使用方法:任何方式都支持,兼容到IE10以上浏览器
前台:不需要任何改动,正常使用ajax请求
后台:文件头部做小小修改
header("Access-Control-Allow-Origin:*");//所有域名都可以访问它
header("Access-Control-Allow-Methods:POST,GET");

推荐3

比较常用的是JSONP方法,JSONP方法是一种非官方方法,而且这种方法只支持GET方式,不如POST方式安全。

即使使用jquery的jsonp方法,type设为POST,也会自动变为GET。

官方问题说明:

“script”: Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, “_=[TIMESTAMP]“, to the URL unless the cache option is set to true.Note: This will turn POSTs into GETs for remote-domain requests.

如果跨域使用POST方式,可以使用创建一个隐藏的iframe来实现,与ajax上传图片原理一样,但这样会比较麻烦。

因此,通过设置Access-Control-Allow-Origin来实现跨域访问比较简单。

例如:客户端的域名是www.client.com,而请求的域名是www.server.com

如果直接使用ajax访问,会有以下错误

XMLHttpRequest cannot load http://www.server.com/server.php. No ‘Access-Control-Allow-Origin‘ header is present on the requested resource.Origin ‘http://www.client.com‘ is therefore not allowed access.

在被请求的Response header中加入

[php] view plain copy

  1. // 指定允许其他域名访问
  2. header(‘Access-Control-Allow-Origin:*‘);
  3. // 响应类型
  4. header(‘Access-Control-Allow-Methods:POST‘);
  5. // 响应头设置
  6. header(‘Access-Control-Allow-Headers:x-requested-with,content-type‘);

就可以实现ajax POST跨域访问了。

代码如下:

client.html 路径:http://www.client.com/client.html

[html] view plain copy

  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  2. <html>
  3. <head>
  4. <meta http-equiv="content-type" content="text/html;charset=utf-8">
  5. <title> 跨域测试 </title>
  6. <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
  7. </head>
  8. <body>
  9. <div id="show"></div>
  10. <script type="text/javascript">
  11. $.post("http://www.server.com/server.php",{name:"fdipzone",gender:"male"})
  12. .done(function(data){
  13. document.getElementById("show").innerHTML = data.name + ‘ ‘ + data.gender;
  14. });
  15. </script>
  16. </body>
  17. </html>

server.php 路径:http://www.server.com/server.php

[php] view plain copy

  1. <?php
  2. $ret = array(
  3. ‘name‘ => isset($_POST[‘name‘])? $_POST[‘name‘] : ‘‘,
  4. ‘gender‘ => isset($_POST[‘gender‘])? $_POST[‘gender‘] : ‘‘
  5. );
  6. header(‘content-type:application:json;charset=utf8‘);
  7. header(‘Access-Control-Allow-Origin:*‘);
  8. header(‘Access-Control-Allow-Methods:POST‘);
  9. header(‘Access-Control-Allow-Headers:x-requested-with,content-type‘);
  10. echo json_encode($ret);
  11. ?>

Access-Control-Allow-Origin:* 表示允许任何域名跨域访问

如果需要指定某域名才允许跨域访问,只需把Access-Control-Allow-Origin:*改为Access-Control-Allow-Origin:允许的域名

例如:header(‘Access-Control-Allow-Origin:http://www.client.com‘);

如果需要设置多个域名允许访问,这里需要用php处理一下

例如允许 www.client.com 与 www.client2.com 可以跨域访问

server.php 修改为

[php] view plain copy

  1. <?php
  2. $ret = array(
  3. ‘name‘ => isset($_POST[‘name‘])? $_POST[‘name‘] : ‘‘,
  4. ‘gender‘ => isset($_POST[‘gender‘])? $_POST[‘gender‘] : ‘‘
  5. );
  6. header(‘content-type:application:json;charset=utf8‘);
  7. $origin = isset($_SERVER[‘HTTP_ORIGIN‘])? $_SERVER[‘HTTP_ORIGIN‘] : ‘‘;
  8. $allow_origin = array(
  9. ‘http://www.client.com‘,
  10. ‘http://www.client2.com‘
  11. );
  12. if(in_array($origin, $allow_origin)){
  13. header(‘Access-Control-Allow-Origin:‘.$origin);
  14. header(‘Access-Control-Allow-Methods:POST‘);
  15. header(‘Access-Control-Allow-Headers:x-requested-with,content-type‘);
  16. }
  17. echo json_encode($ret);
  18. ?>

原文地址:https://www.cnblogs.com/Lzf127/p/8296087.html

时间: 2024-08-19 01:52:54

跨域请求的3种方式的相关文章

解决前端跨域请求的几种方式

利用 JSONP 实现跨域调用 说道跨域调用,可能大家首先想到的或者听说过的就是 JSONP 了. 1.1 什么是JSONP JSONP 是 JSON 的一种使用模式,可以解决主流浏览器的跨域数据访问问题.其原理是根据 XmlHttpRequest 对象受到同源策略的影响,而 <script> 标签元素却不受同源策略影响,可以加载跨域服务器上的脚本,网页可以从其他来源动态产生 JSON 资料.用 JSONP 获取的不是 JSON 数据,而是可以直接运行的 JavaScript 语句. 1.2

System.Web.Http.Cors配置跨域访问的两种方式

System.Web.Http.Cors配置跨域访问的两种方式 使用System.Web.Http.Cors配置跨域访问,众多大神已经发布了很多文章,我就不在详细描述了,作为小白我只说一下自己的使用心得.在webapi中使用System.Web.Http.Cors配置跨域信息可以有两种方式.  一种是在App_Start.WebApiConfig.cs的Register中配置如下代码,这种方式将在所有的webapi Controller里面起作用. using System; using Sys

jQuery 跨域访问的三种方式 No &#39;Access-Control-Allow-Origin&#39; header is present on the reque

问题: XMLHttpRequest cannot load http://v.xxx.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access. test.html:1 Resource interpreted as Script but transferred

实现跨域请求的4种方法

模拟服务器端的PHP文件: service: <?php//允许访问header('Access-Control-Allow-Origin:*');@$callback=$_GET['callback'];//创建数据$userInfo = array('id'=>1,'username'=>'Scott Jeremy','email'=>'[email protected]');//编译成JSON$result = json_encode($userInfo);echo $cal

项目中经常遇到的跨域请求的几种方法

什么是跨域 JSONP proxy代理 cors xdr 关于跨域无非就是jsonp和iframe,随着跨域请求的应用越来越多,W3C提供了跨域请求的标准方案(Cross-Origin Resource Sharing).IE8.Firefox 3.5 及其以后的版本.Chrome浏览器.Safari 4 等已经实现了 Cross-Origin Resource Sharing 规范,实现了跨域请求.在服务器响应客户端的时候,带上Access-Control-Allow-Origin头信息. 如

ASP.NET MVC 实现AJAX跨域请求的两种方法

通常发送AJAX请求都是在本域内完成的,也就是向本域内的某个URL发送请求,完成部分页面的刷新.但有的时候需要向其它域发送AJAX请求,完成数据的加载,例如Google. 在ASP.NET MVC 框架里实现跨域的AJAX请求有几种方式可以实现,以下就介绍常用的两种方法. 1.     发送JSONP请求 客户端: JQuery对发送JSONP请求有很好的支持,客户端通过. ajax() 函数发送请求,其中需要制定 dataType 为“jsonp”  jsonpCallback 为指定的回调函

实践解决跨域问题的三种方式剖析

最近在做我星际schub网站的时候,遇到了跨域问题,我先把后端node部署在了服务器上,然后在本地localhost测试,出现了问题: 浏览器都提示我们使用这个header头: 解决办法: 1. CORS 服务器设置响应头: response.setHeader("Access-Control-Allow-Origin", "*") (这样可能引起CSRF攻击,一般设置成对应的域名就行, response.setHeader("Access-Control

跨域请求的三种解决

第一种:jsonp的方式 <?php header('Content-type: application/json'); //获取回调函数名 $jsoncallback = $_GET['jsoncallback']; //json数据 $json_data = '{"data":[{"did":"29","deptName":"\u8f6f\u4ef6\u90e8"}, {"did&quo

跨域请求的两种实现方式

Jsonp 域1 index.html <script> $(".get-service").click(function () { $.ajax({ url: "http://127.0.0.1:8005/service/", type: "get", dataType: "jsonp", jsonp: "callbacks", // 伪造ajax, 基于script // jsonpCall