jqueryをjsに挿入


置換コード
$(document).ready(function(){
    exchangeRate()
    showList()
});
function exchangeRate(){

    $.ajax({
      type: "GET",
      url: "http://spartacodingclub.shop/sparta_api/rate",
      data: {},
      success: function(response){
          let rate = response['rate']
          $('#exchange-rate').text(rate)
      }
    })
}
function completeOrder() {
    const name = $('#user-name').val()
    const number = $('#user-number').val()
    const address = $('#user-address').val()
    const call = $('#user-call').val()
    $.ajax({
        type: "POST",
        url: "/order",
        data: {
            'name':name,
            'number':number,
            'address':address,
            'call':call,
        },
        success: function (response){
            console.log(response['msg'])
        }
    })
}
function showList(){
    $.ajax({
        type: "GET",
        url: "/order",
        data: {},
        success: function (response){
            let userInfo = response['all_userInfo']
            for (let i = 0; i < userInfo.length; i++){
                let name = userInfo[i]['name']
                let number = userInfo[i]['number']
                let address = userInfo[i]['address']
                let call = userInfo[i]['call']

                let temp_html = `<tr>
                                    <th scope="row">${name}</th>
                                    <td>${number}</td>
                                    <td>${address}</td>
                                    <td>${call}</td>
                                </tr>
                `
                $('#info-list').append(temp_html)
            }
        }
    })
}
(Flashに書き込み中)
まず、ready()を修正します.
$(document).ready(function(){
     exchangeRate()
     showList()
});
似たようなイベントはLoadとDOMContLoadがあり、MDNでは
loadは、スタイルシートや画像など、関連するすべてのリソースを含むページ全体がロードされたときにトリガーされます.
最初のHTMLドキュメントが完全にロードされ解析されると、DOMContentLoadedは、スタイルシート、画像、サブフレームワークのロードが完了するのを待つことなく、THEMCONtentLoadedイベントをトリガーします.
この2つの関数はすべてのコンテンツのロードを待つ必要がないので、DOMContentLoadを使用します.
window.addEventListener('DOMContentLoaded', (event) => {
    exchangeRate()
    showList()
})
今回はajaxにしましょう
function exchangeRate(){
$.ajax({
       type: "GET",
       url: "http://spartacodingclub.shop/sparta_api/rate",
       data: {},
       success: function(response){
           let rate = response['rate']
          $('#exchange-rate').text(rate)
       }
     })
}
ajaxのjsバージョンfetch()に変更
async function exchangeRate(){
    const RATE_URL = "http://spartacodingclub.shop/sparta_api/rate"
    const rate = await fetch(RATE_URL,{
        method: "GET",
        headers: {
            'Content-Type': 'application/json;charset=utf-8'
        },
    }).then(response => response.json()).then(data => data.rate)
    const $exchangeRate = document.querySelector('#exchange-rate')
    $exchangeRate.innerText = rate
元々はfetch()にして地獄にしたかったのですが、友人がそれより良いと言っていたので変えました.
fetchの前で待ってrateに値を割り当てるのを待って、innerTextを埋め込みます.関数で待つ場合は、関数の前にasyncを付けます.
ajax jsの使用
function showList(){
$.ajax({
         type: "GET",
         url: "/order",
         data: {},
         success: function (response){
             let userInfo = response['all_userInfo']
             for (let i = 0; i < userInfo.length; i++){
                 let name = userInfo[i]['name']
                 let number = userInfo[i]['number']
                 let address = userInfo[i]['address']
                 let call = userInfo[i]['call']

                 let temp_html = `<tr>
                                     <th scope="row">${name}</th>
                                     <td>${number}</td>
                                     <td>${address}</td>
                                     <td>${call}</td>
                                 </tr>
                 `
                 $('#info-list').append(temp_html)
             }
         }
     })
}
さっきとあまり違わないタイプ下部のappend()部分だけが違います.
async function showList(){
    const userInfo = await fetch('/order',{
        method: "GET",
        headers: {
            'Content-Type': 'application/json;charset=utf-8'
        },
    }).then(response => response.json()).then(data => data['all_userInfo'])
    const $infoList = document.querySelector('#info-list')
    for (let i = 0; i < userInfo.length; i++){
        let name = userInfo[i]['name']
        let number = userInfo[i]['number'] 
        let address = userInfo[i]['address']
        let call = userInfo[i]['call']
        let temp_html = `<tr>
                            <th scope="row">${name}</th>
                            <td>${number}</td>
                            <td>${address}</td>
                            <td>${call}</td>
                        </tr>
                        `
        $infoList.insertAdjacentHTML('beforeend',temp_html)
    }
以前友人がjsを触っていた時にinsertAdjacentHTML()が本当に良かったと説明していましたが、ふと思い出したのですぐに見つけました.InsertAdjacentHTML()でデータをインポートし、テーブルに入れます.
実はこの部分のためこの招待状を書いたのです.
さっきはajax get形式でしたが、今回はajax post形式です.
function completeOrder() {
    let name = $('#user-name').val()
    let number = $('#user-number').val()
    let address = $('#user-address').val()
    let call = $('#user-call').val()
    $.ajax({
        type: "POST",
        url: "/order",
        data: {
            'name':name,
            'number':number,
            'address':address,
            'call':call,
        },
        success: function (response){
            console.log(response['msg'])
        }
    })
}
ポスト形式で送った時は、最初は考えがなかっただけ
見出しセクション
コンテンツタイプ:アプリケーション/jsonを埋め込む
bodyもJSONstringify({})形式で送信される
400bad request unexpected token < in json at position 0
この間違いはずっと私のノートパソコンと雪合戦をしていて、最初は当たり前だったcontent-typeを疑っていました.
ajaxがサーバに送信するデータ型から見るとjsonではありません.
アプリケーション/x-www-form-urlcodedとして送信されます.
(ajaxが送信したデータ型検証では、フラスコのrequestオブジェクトrequest.content typeが使用されています.)
body部分は上のタイプをgoogleに打つのでmdnでは
application/x-www-form-urlencoded: the keys and values are encoded in key-value tuples separated by '&', with a '=' between the key and the value. Non-alphanumeric characters in both keys and values are percent encoded: this is the reason why this type is not suitable to use with binary data (use multipart/form-data instead)

だからそのまま入れました
async function completeOrder() {
    const name = document.querySelector('#user-name').value
    const number = document.querySelector('#user-number').value
    const address = document.querySelector('#user-address').value
    const call = document.querySelector('#user-call').value
    const msg = await fetch('/order',{
        method: "POST",
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        body: `name=${name}&number=${number}&address=${address}&call=${call}`
    })
    .then(response => response.json()).then(data => data['msg'])
    .catch(error => console.log(error))
    console.log(msg)
}
追加
content-type部分がちょっとおかしいので、もう一度探してみます.
フラスコドキュメント
property form: ImmutableMultiDict[str, str] The form parameters. By default an ImmutableMultiDict is returned from this function. This can be changed by setting parameter_storage_class to a different type. This might be necessary if the order of the form data is important.

すなわち,パラメータとしてデータを受信し,不変のMultiDictで返す.
だからデータを送るときはname=「厳俊植」&age=「13」という方法で送る、request.もしあなたが私にformをくれたら.
データはMultiDict([(name,厳俊植),(age,13)])である.
だから厳俊植のデータを手に入れたいならお願いします.元はform[name]でいいです.(キーは「name」、値は「厳俊植」)
A MultiDict can be constructed from an iterable of (key, value) tuples, a dict, a MultiDict or from Werkzeug 0.2 onwards some keyword parameters. https://werkzeug.palletsprojects.com/en/2.0.x/datastructures/#werkzeug.datastructures.MultiDict

参照リクエストとして使用します.formはpostやputリクエストにしか使えないそうです.
Changed in version 0.9: Previous to Werkzeug 0.9 this would only contain form data for POST and PUT requests.

その後fetchでheadersのcontent-type部分を削除して送信しようとしたが、送信しなかった.すなわちcontent-type明示を忘れてはならない.
考えてみれば、jqueryで書かれたajaxはcontent-typeを自動的に指定し、データフォーマットも自動変換して送信します.
関連条項:https://github.com/golddong98/prac
置換コード
window.addEventListener('DOMContentLoaded', (event) => {
    exchangeRate()
    showList()
})

async function exchangeRate(){
    const RATE_URL = "http://spartacodingclub.shop/sparta_api/rate"
    const rate = await fetch(RATE_URL,{
        method: "GET",
        headers: {
            'Content-Type': 'application/json;charset=utf-8'
        },
    }).then(response => response.json()).then(data => data.rate)
    const $exchangeRate = document.querySelector('#exchange-rate')
    $exchangeRate.innerText = rate

}
async function completeOrder() {
    let name = document.querySelector('#user-name').value
    let number = document.querySelector('#user-number').value
    let address = document.querySelector('#user-address').value
    let call = document.querySelector('#user-call').value
    const msg = await fetch('/order',{
        method: "POST",
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        body: `name=${name}&number=${number}&address=${address}&call=${call}`
    })
    .then(response => response.json()).then(data => data['msg'])
    .catch(error => console.log(error))
    console.log(msg)

}
async function showList(){
    const userInfo = await fetch('/order',{
        method: "GET",
        headers: {
            'Content-Type': 'application/json;charset=utf-8'
        },
    }).then(response => response.json()).then(data => data['all_userInfo'])
    const $infoList = document.querySelector('#info-list')
    for (let i = 0; i < userInfo.length; i++){
        let name = userInfo[i]['name']
        let number = userInfo[i]['number'] 
        let address = userInfo[i]['address']
        let call = userInfo[i]['call']
        let temp_html = `<tr>
                            <th scope="row">${name}</th>
                            <td>${number}</td>
                            <td>${address}</td>
                            <td>${call}</td>
                        </tr>
                        `
        $infoList.insertAdjacentHTML('beforeend',temp_html)
    }

}
結論:無知なjson巨人にならないで