function ajaxGet(option) { if (!option.url) { return alert('url 必传'); } let xhr = new XMLHttpRequest(); let str = ''; if (option.query) { str = '?'; for (let key in option.query) { str += `${encodeURIComponent(key)}=${encodeURIComponent(option.query[key])}&`; } str = str.slice(0, -1); // 去掉最后的 & } xhr.open('GET', option.url + str); xhr.send(); xhr.onreadystatechange = () => { if (xhr.readyState === 4) { if (xhr.status === 200) { option.success && option.success(xhr.responseText); } else { option.error && option.error(xhr.responseText); } } }; } // 使用示例 ajaxGet({ url: '2024demo.txt', query: { name: 'zhangsanfeng', age: 20 }, success: (data) => { console.log(data); }, error: (err) => { console.error(err); } });