H5+ 跨域XMLHttpRequest的坑
来源:互联网 发布:算法公平和效率 知乎 编辑:程序博客网 时间:2024/06/06 10:44
官方文档中的案例为:
function testXHR(){ if(xhr){ return; } xhr=new plus.net.XMLHttpRequest(); xhr.onreadystatechange=function(){ console.log("onreadystatechange: "+xhr.readyState); } xhr.open( "POST", "http://demo.dcloud.net.cn/test/xhr/post.php" ); var data={name:'HBuilder',version:'0.1.0'}; // 发送HTTP请求 xhr.send(JSON.stringify(data));//错误}
注意,发送的数据data请勿用JSON.stringfy(data)发送,后台无法正确获取数据,请求方式为POST,请使用 xhr.send(‘A=xxxx&B=xxxx’)的形式,并且将头部信息更改为:xhr.setRequestHeader(‘Content-Type’,’application/x-www-form-urlencoded’);
(XMLHttpRequest默认提交的content-type为“text/plain;charset=UTF-8”)body: ( String ) 可选 请求HTTP提交的数据内容
当open方法中设置的method参数为POST时必需传入body值。(官方文档也是错误的,可以不传值)Get的形式,则直接在open后面增加参数,最后xhr.send()不允许有值。
xhr.open( “GET”, “http://www.cgrandsoft.cn/test.php?”+’name=an&b=a’);
例子:
//重复提交请求,请勿使用官方例子,会出现不必要的错误,如以下注释部分【以下注释部分写法无法重复提交请求,未知错误】/*switch ( xhr.readyState ) { case 0: alert( "xhr请求已初始化" ); break; case 1: alert( "xhr请求已打开" ); break; case 2: alert( "xhr请求已发送" ); break; case 3: alert( "xhr请求已响应"); break; case 4: if ( xhr.status == 200 ) { alert( "xhr请求成功:"+xhr.responseText ); } else { alert( "xhr请求失败:"+xhr.readyState ); } break; default : break; }*/document.addEventListener('plusready', function(){var xhr;$('button').on('click',function(){xhr = new plus.net.XMLHttpRequest();xhr.onreadystatechange = function () { switch ( xhr.readyState ) { case 4: if ( xhr.status == 200 ) { alert( "xhr请求成功:"+xhr.responseText ); } else { alert( "xhr请求失败:"+xhr.readyState ); } break; }}xhr.open( "POST", "http://www.xxxxx.cn/test.php");xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');xhr.send('name=hehe');})}, false );
阅读全文
0 0
- H5+ 跨域XMLHttpRequest的坑
- xmlHttpRequest 的创建
- XMLHTTPRequest 的用法
- XMLHttpRequest 对象的使用
- XMLHttpRequest的readyState
- XMLHttpRequest的status
- XMLHttpRequest对象的属性
- xmlhttprequest对象的创建
- XMLHttpRequest对象的理解
- JavaScript XMLHttpRequest的用处
- XmlHttpRequest对象的方法
- Chorme的xmlhttprequest调用
- Ajax的window.XMLHttpRequest
- ajax的XMLHttpRequest对象
- XMLHttpRequest 的介绍
- XMLHttpRequest的创建过程
- XMLHttpRequest对象的创建
- Ajax的XMLHttpRequest对象
- "CSRF token missing or incorrect."的解决办法
- D3D管线以及着色器工作原理-画一个三角形
- spring-security过滤链(一):过滤链
- ubuntu下virtualbox配置host-only网络
- 如何在Java中创建一个矩形类,并通过set()传入长与宽,计算矩形的周长与面积并通过get()查看计算结果
- H5+ 跨域XMLHttpRequest的坑
- 2016微软探星夏令营在线技术笔试-#1341 : Constraint Checker
- MDC介绍 -- 一种多线程下日志管理实践方式
- webconfig 中的 configSections 自定义节点
- 并发中的i++安全问题浅述
- ScrollView嵌套webview,webview跳转后页面不能置顶
- 先验概率与后验概率的区别
- vsftpd配置文件详解
- BZOJ 1050 旅行comf