萬戶網(wǎng)站免費手游推廣平臺
jquery 自帶的 $.ajax() 函數(shù)簡單案例
// 自定義構造一個特定的函數(shù)用來通用請求
function http(url, data, method, success, fail) {// 三元運算符判斷method為get or post,post數(shù)據(jù)需要JSON.stringify()來格式化后再提交給后臺data = method === 'GET' ? data : JSON.stringify(data);$.ajax({url = url,method = method,dataType = 'json',contentType = 'application/json; charset=UTF-8',data = data, //這行不能省略,如果沒有數(shù)據(jù)向后臺提交也要寫成data:{}的形式success = success,error = fail});
}
調用http函數(shù)來請求接口并獲取數(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請求$('get_button').click(get_url)// post 請求$('post_botton').click(post_url)
});
function get_url() {var url = 'http://xxxxxxxxxxxxxx'; // 要請求的接口URLvar send_data = {}; // //這行不能省略,如果沒有數(shù)據(jù)向后臺提交也要寫成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]); // 打印在控制臺顯示獲取到的數(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))});
}