网页和Ajax和跨域的关系

1 Ajax使网页可以动态地、异步地的与服务器进行数据交互,可以让网页局部地与服务器进行数据交互
2 Ajax强调的是异步,但是会碰到跨域的问题。
3 而有很多技术可以解决跨域问题。
eg:很多公共地图,身份证查询的API都使用了CORS技术,在respons headers里面做了设置。

一、JSON 介绍

1. JSON: JavaScript Object Notation

是一种轻量级的数据交换格式。 它基于ECMAScript的一个子集。 JSON采用完全独立于语言的文本格式(多种后台语言都可以处理json,就很充分的说明了这一点),但是也使用了类似于C语言家族的习惯(包括C、C++、C#、Java、JavaScript、Perl、Python等)。这些特性使JSON成为理想的数据交换语言。
Because of this similarity, instead of using a parser (like XML does), a JavaScript program can use standard JavaScript functions to convert JSON data into native JavaScript objects. 
The JSON syntax is a subset of the JavaScript syntax.   JSON 语法是 JavaScript 语法的子集。 
JSON Uses JavaScript Syntax
Because JSON syntax is derived from JavaScript object notation, very little extra software is needed to work with JSON within JavaScript. 
JSON values can be:
A number (integer or floating point)
A string (in double quotes)
A Boolean (true or false)
An array (in square brackets)
An object (in curly braces)
null 

2. Javascript中的JSON对象 MDN

The JSON object contains methods for parsing JavaScript Object Notation (JSON) and converting values to JSON. It can't be called or constructed, and aside from its two method properties it has no interesting functionality of its own.
两个方法:
1、    JSON.parse()        把JSON object 转化成 javascript中的 数值类型
2、    JSON.stringify()     恰好相反

3.  Josn解析

二、AJAX

wiki

Ajax (short for asynchronous JavaScript and XML(XML只是之前名字的来历,现在更多的是json格式的数据交换,当然也有其它数据格式)) is a set of(多种技术的合集) web development techniques using many web technologies on the client-side to create asynchronous Web applications. With Ajax, web applications can send data to and retrieve from a server asynchronously (in the background) without interfering with the display and behavior of the existing page. By decoupling the data interchange layer from the presentation layer, Ajax allows for web pages, and by extension web applications, to change content dynamically without the need to reload the entire page(允许网页或是web应用来动态地、异步地的交换数据). In practice, modern implementations commonly substitute JSON for XML(现在更多使用json代替xml) due to the advantages of being native to JavaScript.

Ajax is not a technology, but a group of technologies. HTML and CSS can be used in combination to mark up and style information. The DOM is accessed with JavaScript to dynamically display – and allow the user to interact with – the information presented. JavaScript and the XMLHttpRequest object provide a method for exchanging data asynchronously between browser and server to avoid full page reloads.

 Asynchronous JavaScript + XML,(MDN) while not a technology in itself, is a term coined (不是新技术,而是一种术语)in 2005 by Jesse James Garrett, that describes a "new" approach to using a number of existing technologies together, including: HTML or XHTML, Cascading Style Sheets, JavaScript,The Document Object Model, XML, XSLT, and most importantly the XMLHttpRequest object.   (The keystone of AJAX is the XMLHttpRequest object.)
AJAX is a misleading name. You don't have to understand XML to use AJAX.

1 The XMLHttpRequest Object   (MDN)

创建xhr对象
All modern browsers support the XMLHttpRequest object.
eg:

var xhttp;
if (window.XMLHttpRequest) {
    xhttp = new XMLHttpRequest();
    } else {
    // code for IE6, IE5
    xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

2  http请求

So essentially GET is used to retrieve remote data, and POST is used to insert/update remote data.
XHR(XMLHttpRequest 对象)的属性中的三个:

1. status

  • 1xx:指示信息--表示请求已接收,继续处理。
  • 2xx:成功--表示请求已被成功接收、理解、接受。
  • 3xx:重定向--要完成请求必须进行更进一步的操作。
  • 4xx:客户端错误--请求有语法错误或请求无法实现。
  • 5xx:服务器端错误--服务器未能实现合法的请求。

100——客户必须继续发出请求
  101——客户要求服务器根据请求转换HTTP协议版本
  200——成功
  201——提示知道新文件的URL
  300——请求的资源可在多处得到
  301——删除请求数据
  404——没有发现文件、查询或URl
  500——服务器产生内部错误

2. readyState

存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。

0: 请求未初始化,open()方法还没有调用

1: 服务器连接已建立

2: 请求已接收,接收到头信息了

3: 请求处理中,接收到响应主体了

4: 请求已完成,且响应已就绪,也就是相应已经完成了

3. onreadystatechange

An EventHandler that is called whenever the readyState attribute changes. The callback is called from the user interface thread.

request.open(method,url,asy)

requset.send(string)

如果是get请求,则参数直接拼接在url里面了

如果是send请求,则参数需要写在send()方法里面

post请求

function post(){

var req = createXMLHTTPRequest();

if(req){

req.open("POST", "http://test.com/", true);

req.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=gbk;");

req.send("keywords=手机");

req.onreadystatechange = function(){

if(req.readyState == 4){

if(req.status == 200){

alert("success");

}else{

alert("error");

}

}

}

}

}

get请求

function get(){  

var req = createXMLHTTPRequest();

if(req){

req.open("GET", "http://test.com/?keywords=手机", true);

req.onreadystatechange = function(){

if(req.readyState == 4){

if(req.status == 200){

alert("success");

}else{

alert("error");

}

}

}

req.send(null);

}

}

三、同源策略

浏览器同源政策及其规避方法

同源策略

同源策略限制了一个源(origin)中加载文本或脚本与来自其它源(origin)中资源的交互方式。

同源政策的目的,是为了保证用户信息的安全,防止恶意的网站窃取数据。

如果非同源,共有三种行为受到限制。

  • (1) Cookie、LocalStorage 和 IndexDB 无法读取。
  • (2) DOM 无法获得。
  • (3) AJAX 请求不能发送。

Cookie

Cookie总是保存在客户端中,按在客户端中的存储位置,可分为内存Cookie和硬盘Cookie。

四、跨域

跨域的含义

 只要协议、域名、端口有任何一个不同,都被当作是不同的域
javascript出于安全方面的考虑,不允许跨域调用其它页面的对象
 

同源政策规定,AJAX请求只能发给同源的网址,否则就报错。

除了架设服务器代理(浏览器请求同源服务器,再由后者请求外部服务),有三种方法规避这个限制。

  • JSONP
  • WebSocket
  • CORS

解决跨域问题的几种方法:

1 JSONP

说说JSON和JSONP,也许你会豁然开朗,含jQuery用例

JSON是一种数据交换格式,而JSONP是一种依靠开发人员的聪明才智创造出的一种非官方跨域数据交互协议。
JSONP (JSON with Padding or JSON-P) is a technique used by web developers to overcome(克服跨域限制) the cross-domain restrictions imposed by browsers' same-origin policythat limits access to resources retrieved from origins other than the one the page was served by.
 基本思想是,网页通过添加一个<script>元素,向服务器请求JSON数据,这种做法不受同源政策限制;服务器收到请求后,将数据放在一个指定名字的回调函数里传回来。
 该协议的一个要点就是允许用户传递一个callback参数给服务端,然后服务端返回数据时会将这个callback参数作为函数名来包裹住JSON数据,这样客户端就可以随意定制自己的函数来自动处理返回数据了.
可以这样理解:自己先写好一个回调函数,然后让“服务器调用”。

2 WebSocket

3 CORS

CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。
The CORS standard describes new HTTP headers(新的请求头) which provide browsers and servers a way to request remote URLs only when they have permission(当有“许可”时).

The HTTP headers that relate to CORS are:

Request headers

  • Origin
  • Access-Control-Request-Method
  • Access-Control-Request-Headers

Response headers

  • Access-Control-Allow-Origin
  • Access-Control-Allow-Credentials
  • Access-Control-Expose-Headers
  • Access-Control-Max-Age
  • Access-Control-Allow-Methods
  • Access-Control-Allow-Headers

CORS vs JSONP

CORS can be used as a modern alternative(现代浏览器替换jsonp的模式) to the JSONP pattern.

While JSONP supports only the GET request method, CORS also supports other types(支持其它请求) of HTTP requests.

Using CORS enables a web programmer to use regular XMLHttpRequest, which supports better error handling than JSONP.

On the other hand, JSONP works on legacy browsers(老式浏览器) which predate CORS support. CORS is supported by most modern web browsers. Also, while JSONP can cause cross-site scripting (XSS) issues where the external site is compromised, CORS allows websites to manually parse responses to ensure security.

CORS

CORS需要浏览器和服务器同时支持。目前,所有浏览器都支持该功能,IE浏览器不能低于IE10

整个CORS通信过程,都是浏览器自动完成,不需要用户参与。对于开发者来说,CORS通信与同源的AJAX通信没有差别,代码完全一样。浏览器一旦发现AJAX请求跨源,就会自动添加一些附加的头信息,有时还会多出一次附加的请求,但用户不会有感觉。

因此,实现CORS通信的关键是服务器。只要服务器实现了CORS接口,就可以跨源通信。

 

JavaScript JSON timer(计时器) AJAX HTTP请求 同源策略 跨域请求的更多相关文章

  1. JavaScript JSON AJAX 同源策略 跨域请求

    网页和Ajax和跨域的关系 1 Ajax使网页可以动态地.异步地的与服务器进行数据交互,可以让网页局部地与服务器进行数据交互 2 Ajax强调的是异步,但是会碰到跨域的问题. 3 而有很多技术可以解决 ...

  2. ajax异步请求/同源策略/跨域传值

    基本概念 Ajax 全称是异步的 JavaScript 和 XML . 通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新.这意味着可以在不重新加载整个网页的情况下,对网页的某部分进 ...

  3. 客户端ajax请求为实现Token验证添加headers后导致正常请求变为options跨域请求解决方法

    客户端为了实现token认证,通过Jquery的ajaxSetup方法全局配置headers: 全局配置headers后会导致部分不需要token认证的请求变为options请求,导致跨域访问.报错信 ...

  4. AJAX(XMLHttpRequest)进行跨域请求方法详解

    AJAX(XMLHttpRequest)进行跨域请求方法详解(三) 2010年01月11日 08:48:00 阅读数:24213 注意:以下代码请在Firefox 3.5.Chrome 3.0.Saf ...

  5. 4 伪ajax:jsonp、cors 跨域请求

    一.同源策略 https://www.cnblogs.com/yuanchenqi/articles/7638956.html 同源策略(Same origin policy)是一种约定,它是浏览器最 ...

  6. JSON和JSONP有哪些区别,PhoneGap跨域请求如何实现

    前言 由于Sencha Touch 2这种开发模式的特性,基本决定了它原生的数据交互行为几乎只能通过AJAX来实现. 当然了,通过调用强大的PhoneGap插件然后打包,你可以实现100%的Socke ...

  7. AJAX(XMLHttpRequest)进行跨域请求方法详解(一)

    注意:以下代码请在Firefox 3.5.Chrome 3.0.Safari 4之后的版本中进行测试.IE8的实现方法与其他浏览不同. 跨域请求,顾名思义,就是一个站点中的资源去访问另外一个不同域名站 ...

  8. AJAX(XMLHttpRequest)进行跨域请求方法详解(三)

    注意:以下代码请在Firefox 3.5.Chrome 3.0.Safari 4之后的版本中进行测试.IE8的实现方法与其他浏览不同. 3,带验证信息的请求 身份验证是Web开发中经常遇到的问题,在跨 ...

  9. AJAX(XMLHttpRequest)进行跨域请求方法详解(二)

    注意:以下代码请在Firefox 3.5.Chrome 3.0.Safari 4之后的版本中进行测试.IE8的实现方法与其他浏览不同. 2,预检请求 预检请求首先需要向另外一个域名的资源发送一个 HT ...

随机推荐

  1. [ An Ac a Day ^_^ ] POJ 3254 Corn Fields 状压dp

    题意: 有一块n*m的土地 0代表不肥沃不可以放牛 1代表肥沃可以放牛 且相邻的草地不能同时放牛 问最多有多少种放牛的方法并对1e8取模 思路: 典型的状压dp 能状态压缩 能状态转移 能状态压缩的题 ...

  2. ps -ef |grep 输出的具体含义

    [root@localhost ~]# ps -ef | grep ApacheJetspeed root     18887 18828  0 08:09 pts/0    00:00:00 gre ...

  3. Meta标签中的format-detection属性及含义让IPHONE的数字可以改变颜色

    format-detection翻译成中文的意思是“格式检测”,顾名思义,它是用来检测html里的一些格式的,那关于meta的format-detection属性主要是有以下几个设置: meta na ...

  4. Docker 总结

    版权声明:本文为博主原创文章,未经博主允许不得转载.   目录(?)[+] Docker总结 简单介绍 1 Docker 架构 安装和环境配置 1 mac 11 brew安装 11 dmg文件安装 1 ...

  5. 取消a标签在移动端点击时的背景颜色

    一.取消a标签在移动端点击时的蓝色 -webkit-tap-highlight-color: rgba(255, 255, 255, 0); -webkit-user-select: none; -m ...

  6. iOS学习之Runtime(一)

    一.Runtime简介 因为Objective-C是一门动态语言,所以它总是想办法把一些决定性工作从编译链接推迟到运行时,也就是说只有编译器是不够的,还需要一个运行时系统(runtime system ...

  7. meta小解

    meta是html中的一个辅助标签,位于<head>与<title>之间,它能提供用户不可见的信息,数据结构为键值对 meta标签格式<meta http-equiv/n ...

  8. SQL 查询优化 索引优化

    sql语句优化 性能不理想的系统中除了一部分是因为应用程序的负载确实超过了服务器的实际处理能力外,更多的是因为系统存在大量的SQL语句需要优化. 为了获得稳定的执行性能,SQL语句越简单越好.对复杂的 ...

  9. C#调用托管C++类(DLL)

    毕设是做一个网络摄像头的相关应用.界面用WPF,图像处理部分是OpenCV.没用EmguCV的原因是国内EmguCV的资料相对比较少,EmguCV虽然提供了Winform的控件,在做UI上有一定优势, ...

  10. spark-2.0.0与hive-1.2.1整合

    SparkSQL与Hive的整合 1. 拷贝$HIVE_HOME/conf/hive-site.xml和hive-log4j.properties到 $SPARK_HOME/conf/ 2. 在$SP ...