jQuery 與 Ajax


Posted by s103071049 on 2021-07-02

更多 api jQuery 參考

jQuery 的兩個用途,用途一、跨瀏覽器的相關處理(新增、刪除),用途二、aJax 發 request

使用網站:https://restcountries.eu/#api-endpoints-name

jQuery.ajax()

官方文件,文件有他的說明、各個參數的型態、範例,也可以直接 google ajax jQuery example

一、發出請求 $.ajax()

裡面的參數可以傳物件,傳物件的好處是可以指定各個細節。

      $.ajax({
        method: 'GET',
        url: 'https://restcountries.eu/rest/v2/name/taiwan'
      })

如果是 get 可以將上述簡寫

      $.ajax('https://restcountries.eu/rest/v2/name/taiwan')

二、接收結果 .done(cb funct)

      $.ajax({
        method: 'GET',
        url: 'https://restcountries.eu/rest/v2/name/taiwan'
      }).done(function(data) {
        console.log(data)
      })

三、錯誤處理

故意將 url 打錯,url: 'https://restcountries.eu/rest/v2/name/taiwanaaa'

方法一、 .fail( )

.fail(function(err) {
        console.log('error', err)
      })
#完整代碼
      $.ajax({
        method: 'GET',
        url: 'https://restcountries.eu/rest/v2/name/taiwanaaa'
      }).done(function(data) {
        console.log(data)
      }).fail(function(err) {
        console.log('error', err)
      })

方法二、

      $.ajax({
        method: 'GET',
        url: 'https://restcountries.eu/rest/v2/name/taiwan',
        success: data => console.log(data),
        error: err => console.log('err', err)
      })

製作一個國家的搜尋器

先製作前端介面

<body>
    name: <input name="country-name"> <button class='btn'>送出</button>
    <div class="list">
    </div>
</body>

發事件以前,要先 ready

        $(document).ready(() => {
            $('.btn').click(() => {
              const value = $('input[name = country-name]').val()
              if (value === '') {
                alert('必須輸入名稱')
                return
              }
                $('.list').empty()
                $.ajax({
                    method: 'GET',
                    url: 'https://restcountries.eu/rest/v2/name/' + value,
                    success: countries => {
                      for (let country of countries) {
                        $('.list').append(
                    `<div>${country.alpha2Code} ${country.name} ${country.nativeName}</div>`
                        )
                      }
                    },
                    error: err => alert('系統不穩定')
                  })
            })
        })

總結

  1. 可以在 jQuery 官方文件查找用法
  2. jQuery plug in
  3. $() 通常是 jQuery 的語法
  4. $ === jQuery 只是一個簡寫而已

#jquery







Related Posts

[10] 虛擬環境建置

[10] 虛擬環境建置

JS try catch 使用方式

JS try catch 使用方式

MTR04_0612

MTR04_0612


Comments