Tweety-666
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee
  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # 【JS30】Day6 - AJAX Type Ahead ###### tags: `fetch`、`promise`、`同步與非同步`、`正規表達式` 本篇是**接資料**的重點,有3種常見方式。 1. 原生( XMLHttpRequest) 2. ajax 3. fetch 我是先學XMLHttpRequest的用法,但程式碼相對比較複雜、不直觀。後來才學習ajax、fetch的用法。本篇只講述[fetch的用法](https://developer.mozilla.org/zh-TW/docs/Web/API/Fetch_API/Using_Fetch)。 在學習前,最好先理解**同步與非同步**的觀念,才知道為什麼會有這項技術。 (推薦閱讀:[AJAX與Fetch API](https://eyesofkids.gitbooks.io/javascript-start-from-es6/content/part4/ajax_fetch.html)) ## fetch 首先,先定義接口。還有定義一個空陣列,因為之後要把接到的資料推上去這個陣列。 ```fetch```後面會接著```then```,後面會接response。 可以想成是:接上資料的接口(找到門口、敲門) → 得到一個反應(有人應門)。 使用 ```fecth``` 的時候它會先回傳 ```Promise```給我們,第一個回傳的是一個 ```readableStream```,我們需要先把它解析成 ```json ```來讀取。 ```javascript= //定義接口跟空陣列 const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json'; const cities = []; //開始接資料囉 fetch(endpoint) .then(blob => blob.json()) //ES6箭頭函式,接到資料後,轉json .then(data =>console.log(data)) //console後發現data是陣列 .then(data => cities.push(...data)); //data推上cities這個空陣列 ``` 要注意的是上方程式碼範例中,要是不加```... (ES6的spread)```,只寫成: ```javascript= .then(data => cities.push(data)); ``` 推上陣列的資料就會是data陣列本身,而不是陣列內的項目。 <br> ### debug時間 等等,json資料格式不是物件嗎? 為何```.then(data =>console.log(data))```後,會發現data是陣列呢? **fetch後會回傳一個promise**。(要懂這段,必須要了解什麼是promise。) then方法實際上是整個Promise結構的流程運作起來的主要關鍵,then方法之後,剛好傳的data格式是陣列。 OK,開始有點不懂了。 什麼是promise? ## promise 要了解promise,要先知道這個技術為何而生,所以就得了解**同步、非同步**的概念,以及**callback**,然後就會了解到**callback hell**。 這部分我會另外打一份技術筆記。(請看:[同步與非同步、promise、callback的概念](https://hackmd.io/HlQ3Ka0pR7CuT1yrdkm2RQ)) <br> ## 正規表達式 下方程式碼中,```const regex = new RegExp(wordToMatch, 'gi');```是使用**建構式**去呼叫**正規表達式**。 [正規表達式](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Guide/Regular_Expressions)(下方的RegExp)是個看起來很混亂的寫法,是被用來匹配字串中字元組合的模式。 ```new RegExp(regex, flag)```,**第一個參數放的是正規式的內容,第二個參數是 flag。** g 表示 global search,也就是會去找整份文件,而不是找到就停。 i 表示 case insensitive,也就是不去區分大小寫。 ```javascript= function findMatches(wordToMatch, cities) { return cities.filter(place => { // here we need to figure out if the city or state matches what was searched const regex = new RegExp(wordToMatch, 'gi'); return place.city.match(regex) || place.state.match(regex) }); } ``` <br> ## innerHTML 接下來把過濾好的內容,放到html中。 **replace的用法,用於在字符串中用一些字符替換另一些字符,或替換一個與正則表達式匹配的子串。** 語法:```stringObject.replace( regexp/substr , replacement ) ``` ```javascript= //定義各種函式 function numberWithCommas(x) { return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); } function displayMatches() { const matchArray = findMatches(this.value, cities); const html = matchArray.map(place => { const regex = new RegExp(this.value, 'gi'); const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`); const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`); return ` <li> <span class="name">${cityName}, ${stateName}</span> <span class="population">${numberWithCommas(place.population)}</span> </li> `; }).join(''); suggestions.innerHTML = html; //定義好DOM const searchInput = document.querySelector('.search'); const suggestions = document.querySelector('.suggestions'); //監聽DOM,執行函式 searchInput.addEventListener('change', displayMatches); searchInput.addEventListener('keyup', displayMatches); } ``` <br> ## keyup、change、input事件 keyup: 鬆開鍵盤時觸發。 change: 焦點離開元素之前,如果元素有改變的話,就會觸發。 input:會在任何元素值改變的時候被出發(例如每打一個字都會觸發一次)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully