萬(wàn)戶(hù)網(wǎng)站免費(fèi)手游推廣平臺(tái)
jquery 自帶的 $.ajax() 函數(shù)簡(jiǎn)單案例
// 自定義構(gòu)造一個(gè)特定的函數(shù)用來(lái)通用請(qǐng)求
function http(url, data, method, success, fail) {// 三元運(yùn)算符判斷method為get or post,post數(shù)據(jù)需要JSON.stringify()來(lái)格式化后再提交給后臺(tái)data = method === 'GET' ? data : JSON.stringify(data);$.ajax({url = url,method = method,dataType = 'json',contentType = 'application/json; charset=UTF-8',data = data, //這行不能省略,如果沒(méi)有數(shù)據(jù)向后臺(tái)提交也要寫(xiě)成data:{}的形式success = success,error = fail});
}
調(diào)用http函數(shù)來(lái)請(qǐng)求接口并獲取數(shù)據(jù)
1.數(shù)據(jù)格式:
{'status': 0,'message': "ok",'data': [{"name": "python", "price": 10000},{"name": "java", "price": 11000},{"name": "automatic", "price": 8600}]
}
2.js-jquery
$(function () {// get請(qǐng)求$('get_button').click(get_url)// post 請(qǐng)求$('post_botton').click(post_url)
});
function get_url() {var url = 'http://xxxxxxxxxxxxxx'; // 要請(qǐng)求的接口URLvar send_data = {}; // //這行不能省略,如果沒(méi)有數(shù)據(jù)向后臺(tái)提交也要寫(xiě)成data:{}的形式http(url, send_data, 'GET', function(data) {alert(JSON.stringify(data)); // 彈窗顯示從接口獲取到的數(shù)據(jù)for (var i i=0; i<data['data'].length; i++) {console.log(data['data'][i]); // 打印在控制臺(tái)顯示獲取到的數(shù)據(jù)$('#course').append('<div><label>' + data["data"][i]["name"] + '</label><label>' + data["data"][i]["price"] + '</label></div>')}},function(data){alert(JSON.stringify(data)) // 獲取直接alert('error')});
}function post_url() {var url = "http://xxxxxxxxx";var data = {};http(url, data, 'POST', function (data) {alert(data['data'])}, function (data) {alert(JSON.stringify(data))});
}