Ajax代码
//发送数据请求
ajax({
async:false,
url:'http://localhost:9000/register',
type:'POST',
dataType:'json',
data: JSON.stringify(data),
success:function(msg){
var json = JSON.parse(msg);
alert("注册成功!");
if (json.status == "true") {
window.location.href = "http://localhost:9000/login";
}
},
error:function (error) {
alert("error"+error.message);
}
});
返回数据
msg="{status:"true"}"
而且也不执行ERROR,就直接把success和error跳过了
创建Ajax函数,各位前端大佬,帮忙看一下!前端小白甚是感激!
//创建ajax函数
function ajax(options){
options=options||{};
options.type=(options.type||'GET').toUpperCase();
options.dataType=options.dataType||'json';
params = options.data;
//创建-第一步
var xhr;
//非IE6
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}else{
//ie6及其以下版本浏览器
xhr=ActiveXObject('Microsoft.XMLHTTP');
}
//接收-第三步
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status>=200 && xhr.status<300){
options.success&&options.success(xhr.responseText,xhr.responseXML);
}else{
options.error&&options.error(status);
}
}else {
// alert("系统繁忙,请稍后再试!")
}
}
//连接和发送-第二步
if(options.type==='GET'){
xhr.open('GET',options.url+'?'+params,true);
xhr.send(null);
}else if(options.type=='POST'){
xhr.open('POST',options.url,true);
//设置表单提交时的内容类型
xhr.setRequestHeader("Content-Type", "application/json;charset=utf-8");
xhr.send(params);
}
}
各位老师大牛,我找到问题所在了。因为按钮是bootstrap的button,点击会触发bootstrap的强制刷新,倒是页面被刷新。将<button></button>修改为<button type="button"></button>就可以了。非常感谢各位老师大牛!
你这个是需要同步还是异步发送请求?
你这代码不完整呀?你是怎么调用的
在 xhr.onreadystatechange=function(){中 console.log(xhr.status);
输出下xhr.status看看是多少。如果读取的是浏览器缓存会是否3xx,就不执行success。
是不是content-type的问题
在chrome浏览器中,打开F12开发者工具 -> Network面板 ,查看网络请求会否成功和返回的响应结果
ajax({
async:false,
url:'/register',
type:'POST',
dataType:'json',
data: JSON.stringify(data),
success:function(msg){
// var json = JSON.parse(msg);
alert("注册成功!");
alert(msg)
alert(msg.status)
if (msg.status == "true" || msg.status == true) {
window.location.href = "http://localhost:9000/login";
}
},
error:function (error) {
alert("error"+error.message);
}
});
执行一下,看看你msg返回的是个啥。不要上来就转json,要么你后台直接返回true/false;
您好,我是有问必答小助手,你的问题已经有小伙伴为您解答了问题,您看下是否解决了您的问题,可以追评进行沟通哦~
如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~
ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632