javascript:js发送请求

GET请求

$.get("/api/v1.0/user",function(resp){
        // 用户未登录
        if ("4101" == resp.errno) {
              location.href = "/login.html";
        } 
        // 查询到了用户的信息
        else if ("0"== resp.errno){
            $("#user-name").val(resp.data.name);
            if (resp.data.avatar){
                $("#user-avatar").attr("src",resp.data.avatar);
            }
        } 
 },"json");

POST请求

function getCookie(name) {
    var r = document.cookie.match("\\b" + name + "=([^;]*)\\b");
    return r ? r[1] : undefined;
}

var data = {
       mobile:mobile,
       password:passwd
 };


 $.ajax({
            url:"/api/v1.0/sessions",
            type:"post",
            data:jsonData,
            contentType:"application/json",
            dataType:"json",
            headers:{
                "X-CSRFToken":getCookie("csrf_token")
            },
            success:function (data) {
                if (data.errno=="0"){
                    // 登录成功,跳转到主页
                    location.href ="/"
                } else {
                  // 其他错误信息,在页面中展示
                  $("#password-err span").html(errmsg);
                  $("#password-err").show();
                }
            }
});

PUT请求

$.ajax({
            url:"/api/v1.0/users/name",
            type:"PUT",
            data:JSON.stringify({name:name}),
            contentType:"application/json",
            dataType:"json",
            headers:{
                "X-CSRFToken":getCookie("csrf_token")
            },
            success: function (data){
                if ("0" == data.errno) {
                    $(".error-msg").hide();
                    showSuccessMsg();
                } else if ("4001" == data.errno) {
                    $(".error-msg").show();
                } else if ("4101" == data.errno) {
                    location.href = "/login.html";
                }
            }
        });

DELETE请求

$.ajax({
        url:"/api/v1.0/sessions",
        type:"delete",
        headers:{
            "X-CSRFToken":getCookie("csrf_token")
        },
        dataType:"json",
        success: function(resp){
            if ("0" == resp.errno){
                location.href = "/index.html";
            }
        }
 });

你可能感兴趣的:(JavaScript,javascript,json,前端)