发表于: 2019-10-08 17:48:32

1 780


今天完成的事情

完成了js任务五,ajax的相关知识,演示图如下

js代码如下:

var a = document.getElementById("footer");
a.onclick = function () {
    var xhr = new XMLHttpRequest();
    var name = document.getElementById("user").value;
    var pwd = document.getElementById("pwd").value;
    console.log(namepwd);
    xhr.onreadystatechange = function () {
        console.log(xhr);
        if (xhr.readyState === 4 && xhr.status === 200) {
            let data = JSON.parse(xhr.responseText);
            console.log(data);
            if (data.code === 0) {
                alert("登录成功!");
            } else {
                document.getElementById("addText").innerHTML = data.message;
            }
        }
    }
    xhr.open("post""/carrots-admin-ajax/a/login"true);
    xhr.setRequestHeader("Content-type""application/x-www-form-urlencoded");
    xhr.send("name=" + name + "&pwd=" + pwd);
}

jQuery代码如下

$(document).ready(function () { 
    $("button").click(function () {
        var name = $("#user").val();
        var pwd = $("#pwd").val();
        $.ajax({
            type: "post",
            url: "/carrots-admin-ajax/a/login",
            // data: "name=" + name + "&pwd=" + pwd,
            data: {
                name: name,
                pwd: pwd
            },
            success: function (result) {
                console.log(result)
                let data = JSON.parse(result);
                if (data.code === 0) {
                    alert("登录成功!");
                } else {
                    document.getElementById("addText").innerHTML = data.message;
                }
            }
        });
    });
});

nginx配置文件如下

worker_processes 1;
events {
    worker_connections 1024;
}
http {
    include mime.types;
    default_type application/octet-stream;

    sendfile on;
    keepalive_timeout 65;
    server {
        listen   12;
        server_name     localhost;
        location / {
            root    C:\\Users\\Pro\\Desktop\\JS-Task\\;
            index   index.html index.htm;
        }
        location /carrots-admin-ajax/{
            proxy_pass http://dev.admin.carrots.ptteng.com/;
        }
    }
}


今天遇到的问题

1.开始都是在直接打开html文件,发现点击登录时并没有什么反应,忘了这里配置过了nginx文件,要输入http://localhost:12/Task5/打开html文件


2.data.code和data.message这都是与后端相关的,本身返回的数据中就有这两个,可以通过code==0判断来实现页面的跳转,message返回报错的信息,如下图返回信息当code为-5003的时候,message就是显示用户不存在。


3.    xhr.setRequestHeader("Content-type""application/x-www-form-urlencoded");

这是请求头,当使用post的时候,必须加这个,当然,请求的类型不是固定,但是这个是jQuery中默认的类型。不使用会报错。


4.jQuery写法中$(document).ready(function ()的意思:页面加载完才执行以下代码。这行代码使用后,html中不能写on事件,要在js中写。当然,这行代码不写也可以运行。


5.xhr.send("name=" + name + "&pwd=" + pwd);这行代码中的“name"和”&pwd"这个是固定写法,因为接口文档中后端就这这样定义的。如下


今天的收获

如下图,知道了怎么查看ajax请求时的状态,以及返回参数时是什么


明天的计划

学习angular框架



返回列表 返回列表
评论

    分享到