愈來愈少人用JQuery,但你就不學了嗎?(5)

如須要跟多資料請點擊下方圖片⬇(掃碼加好友→備註66)
imagehtml

Jquery Ajax

$.ajax

​ jquery調用ajax方法:jquery

​ 格式:$.ajax({});ajax

​ 參數:json

​ type:請求方式GET/POST服務器

​ url:請求地址urlapp

​ async:是否異步,默認是true表示異步異步

​ data:發送到服務器的數據async

​ dataType:預期服務器返回的數據類型ide

​ contentType:設置請求頭函數

​ success:請求成功時調用此函數

​ error:請求失敗時調用此函數

get請求

$.ajax({
    type:"get",
    url:"js/cuisine_area.json",
    async:true,
    success : function (msg) {
        var str = msg;
        console.log(str);
        $('div').append("<ul></ul>");
        for(var i=0; i<msg.prices.length;i++){
            $('ul').append("<li></li>");
                $('li').eq(i).text(msg.prices[i]);
        }
    },
    error : function (errMsg) {
        console.log(errMsg);
        $('div').html(errMsg.responseText);
    }
});

post請求

$.ajax({
    type:"post",
    data:"name=tom",
    url:"js/cuisine_area.json",
    contentType: "application/x-www-form-urlencoded",
    async:true,
    success : function (msg) {
        var str = msg;
        console.log(str);
        $('div').append("<ul></ul>");
        for(var i=0; i<msg.prices.length;i++){
            $('ul').append("<li></li>");
            $('li').eq(i).text(msg.prices[i]);
        }
    },
    error : function (errMsg) {
        console.log(errMsg);
        $('div').html(errMsg.responseText)
    }
});

$.get

​ 這是一個簡單的 GET 請求功能以取代複雜 $.ajax 。

​ 請求成功時可調用回調函數。若是須要在出錯時執行函數,請使用 $.ajax。

// 1.請求json文件,忽略返回值
$.get('js/cuisine_area.json');
// 2.請求json文件,傳遞參數,忽略返回值
$.get('js/cuisine_area.json',{name:"tom",age:100});
// 3.請求json文件,拿到返回值,請求成功後可拿到返回值
$.get('js/cuisine_area.json',function(data){
    console.log(data);
});
// 4.請求json文件,傳遞參數,拿到返回值    
$.get('js/cuisine_area.json',{name:"tom",age:100},function(data){
    console.log(data);
});

$.post

​ 這是一個簡單的 POST 請求功能以取代複雜 $.ajax 。

​ 請求成功時可調用回調函數。若是須要在出錯時執行函數,請使用 $.ajax。

// 1.請求json文件,忽略返回值
$.post('../js/cuisine_area.json');
// 2.請求json文件,傳遞參數,忽略返回值
$.post('js/cuisine_area.json',{name:"tom",age:100});
// 3.請求json文件,拿到返回值,請求成功後可拿到返回值
$.post('js/cuisine_area.json',function(data){
    console.log(data);
});
// 4.請求json文件,傳遞參數,拿到返回值    
$.post('js/cuisine_area.json',{name:"tom",age:100},function(data){
    console.log(data);
});

$.getJSON

​ 表示請求返回的數據類型是JSON格式的ajax請求

$.getJSON('js/cuisine_area.json',{name:"tom",age:100},function(data){
    console.log(data); // 要求返回的數據格式是JSON格式
});
相關文章
相關標籤/搜索