- 论坛徽章:
- 0
|
场景如下,今天看到 HTML5 关于XMLHttpRequest Level2 的内容, 也就是HTML5的规范中新增加了跨域异步请求的 API , 我按照规范写了一个DEMO,代码如下- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8"/>
- <title>跨域AJAX 数据上传</title>
- <script type="text/javascript">
- function sendData(){
- var xhr = new XMLHttpRequest();
- if(typeof xhr.withCredentials == undefined){
- document.getElementById("support").innerHTML = "抱歉,你的浏览器不支持 跨域异步数据请求";
- return false;
- }else{
- document.getElementById("support").innerHTML = "恭喜,你的浏览器支持 跨域异步数据请求"
- }
- xhr.upload.onprogress = function(e){
- var ratio = e.loaded/e.total;
- setProgress("up",ratio + "% uploaded");
- }
- xhr.onprogress = function(e){
- var ratio = e.loaded/e.total;
- setProgress("down",ratio + "% uploaded");
- }
- xhr.onload = function(e){
-
- setProgress("up","upload compelete.");
- alert(xhr.responseText);
- }
- xhr.onerror = function(e){
- setProgress("up","ERROR");
- }
- var url = "http://my.bbs.com/test.php";
- xhr.withCredentials = true;
- xhr.open("POST",url,true);
- xhr.send("this is a test data for upload");
- }
- function setProgress(id,str){
- document.getElementById(id).innerHTML = str;
- }
- </script>
- </head>
- <body>
- <h1>XMLHttpRequest Level2</h1>
- <input type="button" name="hd" value="上传数据" onclick="sendData()" />
- <div id="support"></div>
- <div id="up"></div>
- <div id="down"></div>
- </body>
- </html>
复制代码 服务器端出来如下
http://my.bbs.com/test.php 这个文件的代码如下- <?php
- header("Expires: -1");
- header("Cache-Control: no-cache");
- header("Access-Control-Allow-Credentials: true");
- header("Access-Control-Allow-Orgin: http://www.yuetong.com");
- header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
- header("Access-Control-Max-Age: max-age=1");
- header("Content-Type: text/html; charset=utf-8");
- print_r($_SERVER);
复制代码 跨域数据请求始终出错, 可以看到HttpFox 请求中看到 错误NS_ERROR_DOM_BAD_URI , 网上查了一下都是说是跨域被浏览器当做错误阻止了,
我测试用的浏览器版本为
不只错误在哪里了
参考文献地址 http://www.html5rocks.com/en/tutorials/cors/ |
|