본문으로 건너뛰기Skip to content
예제 첫화면Examples home

주소에서 받아 행으로 넣기(loadUrl)Load rows from an address (loadUrl)

loadUrl(url, options)는 주소의 JSON·CSV·XML을 받아 행으로 바꿔 넣어요. 형식은 Content-Type, 확장자 순으로 정하고 mode로 바꾸기·붙이기를 골라요. http·https만 받고 주소에 사용자 정보가 있거나 다른 출처이면(allowCrossOrigin 없이) 거절해요. 제한 시간·크기 상한·취소를 지원하고, 받는 동안 로딩 안내를 보이며 loadStarted·loadFinished·loadFailed 이벤트를 내요.loadUrl(url, options) fetches JSON, CSV or XML from an address and puts the rows into the grid. The format comes from Content-Type, then the extension, and mode picks replace or append. Only http and https are accepted, and an address with credentials or a cross-origin one (without allowCrossOrigin) is refused. It supports a timeout, a size limit and cancellation, shows the loading overlay while waiting, and emits loadStarted, loadFinished and loadFailed.

활용Intermediate
직접 써 보기Live preview주소에서 받아 행으로 넣기(loadUrl)Load rows from an address (loadUrl)

코드Code

탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.

이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)

빌드 도구(Vite 등)를 쓰는 프로젝트용 모듈 파일이에요. 설치 없이 바로 돌려 보려면 HTML 탭이나 직접 해보기를 쓰세요.

이 예제는 추가 패키지가 필요해요. 내 컴퓨터에서 돌리려면 npm i maxgrid @maxgrid/export로 설치하세요.

버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="json">JSON 받기</button>
    <button type="button" id="csv">CSV 붙이기</button>
    <button type="button" id="html">HTML 응답</button>
    <button type="button" id="missing">없는 주소</button>
    <button type="button" id="size">크기 상한</button>
    <button type="button" id="abort">중간에 취소</button>
    <button type="button" id="cross">다른 출처</button>
  </div>
  <div id="grid" style="height: 300px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('json').addEventListener('click', () => actions.json(api));
document.getElementById('csv').addEventListener('click', () => actions.csv(api));
document.getElementById('html').addEventListener('click', () => actions.html(api));
document.getElementById('missing').addEventListener('click', () => actions.missing(api));
document.getElementById('size').addEventListener('click', () => actions.size(api));
document.getElementById('abort').addEventListener('click', () => actions.abort(api));
document.getElementById('cross').addEventListener('click', () => actions.cross(api));
example.js
import { withExport } from '@maxgrid/export';
const rows = [{ id: 0, name: '(예전 행)', dept: 'dev', joined: null, active: false }];
export const options = {
  columns: [
    { id: 'id', title: '번호', kind: 'number', width: 70 },
    { id: 'name', title: '이름', width: 150 },
    {
      id: 'dept',
      title: '부서',
      kind: 'select',
      width: 100,
      editorOptions: [
        { value: 'dev', label: '개발' },
        { value: 'ops', label: '운영' },
      ],
      optionLabel: (v) => (v === 'dev' ? '개발' : '운영'),
    },
    { id: 'joined', title: '입사일', kind: 'date', width: 110 },
    { id: 'active', title: '재직', kind: 'boolean', width: 70 },
  ],
  rows,
  rowKey: 'id',
};
// 이 예제는 서버 대신 가짜 fetch를 loadUrl의 `fetch` 옵션으로 넘겨요(전역 fetch는 건드리지 않아요). 실제 앱에서는 옵션 없이 서버 주소를 쓰면 돼요.
// 미리보기 틀 안에서는 상대 주소를 풀 수 없으니 절대 주소를 쓰고 `allowCrossOrigin`을 켜요.
const BASE = 'https://demo.example';
const FAKE = {
  '/people.json': {
    type: 'application/json',
    body: '[{"id":1,"name":"김하늘","dept":"dev","joined":"2024-03-02","active":true},{"id":2,"name":"이도윤","dept":"ops","joined":"2023-11-20","active":false}]',
  },
  '/people.csv': {
    type: 'text/csv',
    body: '번호,이름,부서,입사일,재직\n3,박서연,개발,2025.1.15,예\n4,최지우,운영,,아니오\n',
  },
  '/page.html': { type: 'text/html', body: '<html><body>login</body></html>' },
  '/missing.json': { type: 'text/plain', body: 'not found', status: 404 },
};
const fakeFetch = (async (input, init) => {
  const hit = FAKE[new URL(String(input)).pathname];
  await new Promise((resolve) => setTimeout(resolve, 600)); // 느린 서버
  if (init?.signal?.aborted)
    throw new DOMException('aborted', 'AbortError');
  if (hit === undefined)
    return new Response('', { status: 404 });
  return new Response(hit.body, {
    status: hit.status ?? 200,
    headers: { 'content-type': hit.type },
  });
});
let say = () => { };
let ex;
let pending;
export function setup(api, log) {
  say = log;
  ex = withExport(api);
  const offs = [
    api.on('loadStarted', (e) => log({ ko: `loadStarted ${e.url}`, en: `loadStarted ${e.url}` })),
    api.on('loadFinished', (e) => log({ ko: `loadFinished ${e.count}행`, en: `loadFinished ${e.count} rows` })),
    api.on('loadFailed', (e) => log({ ko: `loadFailed: ${e.message}`, en: `loadFailed: ${e.message}` })),
  ];
  log({
    ko: 'loadUrl(url)은 주소의 데이터를 받아 그리드에 넣어요. 받는 동안 "불러오는 중" 안내가 보여요.',
    en: 'loadUrl(url) fetches data from an address and puts it into the grid. A loading overlay shows while it waits.',
  });
  return () => {
    offs.forEach((off) => off());
    pending?.abort();
  };
}
async function run(url, opts = {}) {
  try {
    await ex?.loadUrl(url, { allowCrossOrigin: true, fetch: fakeFetch, ...opts });
  }
  catch (error) {
    const e = error;
    say({ ko: `실패(${e.code}): ${e.message}`, en: `Failed (${e.code}): ${e.message}` });
  }
}
export const actions = {
  json: () => run(`${BASE}/people.json`),
  csv: () => run(`${BASE}/people.csv`, { mode: 'append', csv: { header: true } }),
  html: () => run(`${BASE}/page.html`, { format: 'json' }),
  missing: () => run(`${BASE}/missing.json`),
  size: () => run(`${BASE}/people.json`, { maxBytes: 60 }),
  abort: () => {
    pending = new AbortController();
    setTimeout(() => pending?.abort(), 250);
    return run(`${BASE}/people.json`, { signal: pending.signal });
  },
  cross: () => run(`${BASE}/people.json`, { allowCrossOrigin: false }),
};

Module files for a project with a bundler such as Vite. To run it with no setup, use the HTML tab or Try it.

This example needs an extra package. To run it locally, install with npm i maxgrid @maxgrid/export.

When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.

index.html
<div id="app">
  <div class="toolbar">
    <button type="button" id="json">Load JSON</button>
    <button type="button" id="csv">Append CSV</button>
    <button type="button" id="html">HTML response</button>
    <button type="button" id="missing">Missing address</button>
    <button type="button" id="size">Size limit</button>
    <button type="button" id="abort">Cancel midway</button>
    <button type="button" id="cross">Cross-origin</button>
  </div>
  <div id="grid" style="height: 300px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('json').addEventListener('click', () => actions.json(api));
document.getElementById('csv').addEventListener('click', () => actions.csv(api));
document.getElementById('html').addEventListener('click', () => actions.html(api));
document.getElementById('missing').addEventListener('click', () => actions.missing(api));
document.getElementById('size').addEventListener('click', () => actions.size(api));
document.getElementById('abort').addEventListener('click', () => actions.abort(api));
document.getElementById('cross').addEventListener('click', () => actions.cross(api));
example.js
import { withExport } from '@maxgrid/export';
const rows = [{ id: 0, name: '(old row)', dept: 'dev', joined: null, active: false }];
export const options = {
  columns: [
    { id: 'id', title: 'No.', kind: 'number', width: 70 },
    { id: 'name', title: 'Name', width: 150 },
    {
      id: 'dept',
      title: 'Department',
      kind: 'select',
      width: 120,
      editorOptions: [
        { value: 'dev', label: 'Dev' },
        { value: 'ops', label: 'Ops' },
      ],
      optionLabel: (v) => (v === 'dev' ? 'Dev' : 'Ops'),
    },
    { id: 'joined', title: 'Joined', kind: 'date', width: 110 },
    { id: 'active', title: 'Active', kind: 'boolean', width: 80 },
  ],
  rows,
  rowKey: 'id',
};
// This example passes a fake fetch to loadUrl through its `fetch` option instead of a server (the global fetch is untouched). A real app uses a server address without the option.
// A relative address cannot be resolved inside the preview frame, so use an absolute address and turn on `allowCrossOrigin`.
const BASE = 'https://demo.example';
const FAKE = {
  '/people.json': {
    type: 'application/json',
    body: '[{"id":1,"name":"Emma Stone","dept":"dev","joined":"2024-03-02","active":true},{"id":2,"name":"Liam Carter","dept":"ops","joined":"2023-11-20","active":false}]',
  },
  '/people.csv': {
    type: 'text/csv',
    body: 'No.,Name,Department,Joined,Active\n3,Noah Reed,Dev,2025.1.15,Yes\n4,Olivia Hayes,Ops,,No\n',
  },
  '/page.html': { type: 'text/html', body: '<html><body>login</body></html>' },
  '/missing.json': { type: 'text/plain', body: 'not found', status: 404 },
};
const fakeFetch = (async (input, init) => {
  const hit = FAKE[new URL(String(input)).pathname];
  await new Promise((resolve) => setTimeout(resolve, 600)); // a slow server
  if (init?.signal?.aborted)
    throw new DOMException('aborted', 'AbortError');
  if (hit === undefined)
    return new Response('', { status: 404 });
  return new Response(hit.body, {
    status: hit.status ?? 200,
    headers: { 'content-type': hit.type },
  });
});
let say = () => { };
let ex;
let pending;
export function setup(api, log) {
  say = log;
  ex = withExport(api);
  const offs = [
    api.on('loadStarted', (e) => log(`loadStarted ${e.url}`)),
    api.on('loadFinished', (e) => log(`loadFinished ${e.count} rows`)),
    api.on('loadFailed', (e) => log(`loadFailed: ${e.message}`)),
  ];
  log('loadUrl(url) fetches data from an address and puts it into the grid. A loading overlay shows while it waits.');
  return () => {
    offs.forEach((off) => off());
    pending?.abort();
  };
}
async function run(url, opts = {}) {
  try {
    await ex?.loadUrl(url, { allowCrossOrigin: true, fetch: fakeFetch, ...opts });
  }
  catch (error) {
    const e = error;
    say(`Failed (${e.code}): ${e.message}`);
  }
}
export const actions = {
  json: () => run(`${BASE}/people.json`),
  csv: () => run(`${BASE}/people.csv`, { mode: 'append', csv: { header: true } }),
  html: () => run(`${BASE}/page.html`, { format: 'json' }),
  missing: () => run(`${BASE}/missing.json`),
  size: () => run(`${BASE}/people.json`, { maxBytes: 60 }),
  abort: () => {
    pending = new AbortController();
    setTimeout(() => pending?.abort(), 250);
    return run(`${BASE}/people.json`, { signal: pending.signal });
  },
  cross: () => run(`${BASE}/people.json`, { allowCrossOrigin: false }),
};