zoukankan      html  css  js  c++  java
  • ajax 设置Access-Control-Allow-Origin实现跨域访问

    ajax跨域访问是一个老问题了,解决方法很多,比较常用的是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中加入

    // 指定允许其他域名访问  
    header('Access-Control-Allow-Origin:*');  
  • 相关阅读:
    CSS3的box-sizing属性
    html5 --基础笔记2
    html5--基础笔记
    CSS3--阴影,渐变,背景图片
    响应式布局--流式布局
    angular中的this指向问题
    angular中控制器之间的通讯方式
    angular中的$http配置和参数
    console
    h5表单验证的css和js方法
  • 原文地址:https://www.cnblogs.com/think-in-java/p/7285359.html
Copyright © 2011-2022 走看看