之前有写过一个项目,前后端分开写的,请求的时候涉及到跨域,所以记下来demo,分享一下。
<script src="jquery-1.11.3.js"></script>//引入js文件
<script> fetch('http://....',{//url地址 async:true,//同步还是异步 method:'POST',//方法 node:'cors', // // headers:{'Content-Type':'application/x-www-form-urlencoded'}, body:JSON.stringify({ userName:$('#userName').val(), password:$('#userPasswd').val() }) }).then(function(response){ console.log(response); if(response.ok){ return response.json() } }).then(function(data){ console.log(data); if(data.result==1){ alert(data.message); //window.location.href="menu.html"; console.log(token); } }).catch(function(e){ console.log("fetch fail",JSON.stringify(e)); }); }); </script>
如果浏览器不兼容,就用jsonp好了,代码如下
if(self.fetch) { // 使用 fetch 方法 } else { // 使用 ajax方法 }
function handleResponse(response){ console.log('The responsed data is: '+response.data); } var script = $('<script></script>'); $('script').attr("src","http://www.baidu.com/json/?callback=handleResponse"); $("body").prepend(script);