JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写,也易于机器解析和生成。它基于JavaScript的一个子集,但独立于语言。
AJAX (Asynchronous JavaScript and XML) 是一种创建快速动态网页的技术,通过在后台与服务器进行少量数据交换,使网页实现异步更新。
// 将JSON对象转换为查询字符串
function jsonToQueryString(json) {
return '?' + Object.keys(json).map(key => {
return encodeURIComponent(key) + '=' + encodeURIComponent(json[key]);
}).join('&');
}
const params = {name: "John", age: 30};
const queryString = jsonToQueryString(params);
fetch(`/api/user${queryString}`)
.then(response => response.json())
.then(data => console.log(data));
const data = {username: 'example', password: '123456'};
fetch('/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
$.ajax({
url: '/api/data',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({key1: 'value1', key2: 'value2'}),
success: function(response) {
console.log(response);
},
error: function(xhr, status, error) {
console.error(error);
}
});
原因:浏览器同源策略限制
解决方案:
原因:
解决方案:
try {
const data = JSON.parse(response);
} catch (e) {
console.error('Invalid JSON:', e);
}
原因:未正确编码/解码特殊字符
解决方案:
encodeURIComponent
/decodeURIComponent
Content-Type
头部(application/json
)fetch
而非传统XMLHttpRequest没有搜到相关的文章