如何调用微信开放平台登录接口-灵析社区

万码F5GTP6P0

在调用微信开放平台时遇到一个问题,使用ajax获取token时,出错。1、type为json时,出现:“ No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '(XX网站域名)' is therefore not allowed access.”2、type为jsonp时,能在chrome的控制台看到返回的数据,但是console里出现:“Uncaught SyntaxError: Unexpected token ”;也无法把返回的数据写到HTML里。以下是代码: <p>第一步,获取code</p> <button id="btn1">用微信登录</button> <p>获取code</p> <button id="btn2">获取code</button> token:<p id="token"></p> openid:<p id="openid"></p> <p>获取用户信息</p> <button id="btn3">获取用户信息</button> <P>姓名:</P><p id="name"></p> <p>头像:</p><img src="" id="img"> <script src="../scripts/jquery-2.1.1.min.js"></script><script src="http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js&quot;></script> var hey = { locationSearch: (function () { var search = window.location.search.substring(1), obj = {}; if (search) { var arr = search.split("&"), length = arr.length; while (length) { var attr = arr[--length].split("="); obj[decodeURIComponent(attr[0])] = !!attr[1] ? decodeURIComponent(attr[1]) : undefined; } } return obj; }()) }; // 第一步,获取Code var btn1=$("#btn1"); var APPID="H";(这里H是一个假设值) var REDIRECT_URI=encodeURIComponent("http://www.XXXXX.com/test/logintext_wechat.html"); var SCOPE="snsapi_login"; btn1.on("click",function(){ window.open("https://open.weixin.qq.com/connect/qrconnect?appid="+APPID+"&redirect_uri="+REDIRECT_URI+"&response_type=code&scope="+SCOPE+"&state=STATE#wechat_redirect") }); // 第二步,获取accessToken var btn2=$("#btn2"); var CODE=hey.locationSearch.code; var SECRET="W";(这里W是一个假设值) var tokenUrl="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+APPID+"&secret="+SECRET+"&code="+CODE+"&grant_type=authorization_code"; btn2.on("click", function () { $.ajax({ url:tokenUrl, type:"get", dataType:"JSONP", success:function(data){ var token=data.access_token; var openid=data.openid; $("#token").html(token); $("#openid").html(openid); } }) }); // 第三步,获取用户信息 var btn3=$("#btn3"); btn3.on("click",function(){ var token3= $("#token").html(); var openid3=$("#openid").html(); var ajaxUrl="https://api.weixin.qq.com/sns/userinfo?access_token="+token3+"&openid="+openid3; $.ajax({ url:ajaxUrl, type:"get", dataType:"JSONP", success:function(data){ var name=$("#name"); var img=$("#img"); $(name).html(data.nickname); $(img).attr("src",data.headimgurl); } }) }) 在第二步获取token时就已经出错了,麻烦有调用微信登录接口的能够指教我一下,谢谢~~

阅读量:118

点赞量:0

问AI
遇到同样的问题,求楼主解决方法!