柚子快报邀请码778899分享:ajaxi:-Ajax介绍 - if(window
柚子快报邀请码778899分享:ajaxi:-Ajax介绍
AJAX(Asynchronous JavaScript and XML)是一种用于创建快速动态网页的技术,它通过在后台与服务器进行少量数据交换,允许在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页内容。
基本概念
Ajax使用流程:
创建XMLHttpRequest对象(不同浏览器实现方式不同)。发送Ajax请求。处理服务器响应。。
数据格式:AJAX可以使用XML、JSON、HTML和文本文件等多种格式进行数据传输,但现在更常用JSON格式。
原生AJAX请求示例
以下是一个简单的原生AJAX请求示例,用于从服务器获取数据并显示在网页上:
function getData() {
var xhr = null;
if(window.XMLHttpRequest){
//IE7+,FireFox,Chrom,Opera,Safari等浏览器
xhr = new XMLHttpRequest();
}
else{
//IE5,IE6浏览器
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var data = JSON.parse(xhr.responseText);
document.getElementById('result').innerHTML = data.message;
}
};
xhr.send();
}
jQuery的AJAX
一、基本语法
$.ajax方法
这是最通用的方式。示例:
$.ajax({
url: 'your - url',
type: 'GET', // 或者'POST'
data: {key1: 'value1', key2: 'value2'},
success: function(response) {
console.log('成功:', response);
},
error: function(xhr, status, error) {
console.log('失败:', error);
}
});
简化的$.get和$.post方法
$.get用于GET请求。例如:
$.get('your - url', {param: 'value'}, function(response) {
console.log('GET成功:', response);
}); 拼多多帮助力入口
$.post用于POST请求。如:
$.post('your - url', {data: 'data'}, function(response) {
console.log('POST成功:', response);
});
二、处理返回数据
JSON数据
如果服务器返回JSON数据,在success回调中可以直接使用。假设返回{"name": "John", "age": 30},可以这样获取值:
success: function(response) {
var name = response.name;
var age = response.age;
}
HTML数据
若返回HTML片段,可以直接将其插入到页面元素中。例如:
success: function(response) {
$('#target - element').html(response);
}
三、设置请求头等高级操作
设置请求头
在$.ajax方法中通过headers属性。例如:
$.ajax({
url: 'your - url',
type: 'POST',
headers: {'Content - Type': 'application/json'},
data: JSON.stringify({key: 'value'}),
success: function(response) {}
});
超时设置
使用timeout属性设置请求超时时间(单位为毫秒)。例如:
$.ajax({
url: 'your - url',
type: 'GET',
timeout: 5000,
success: function(response) {},
error: function(xhr, status, error) {
if (status === 'timeout') {
console.log('请求超时');
}
}
});
柚子快报邀请码778899分享:ajaxi:-Ajax介绍