如何将变量从 html 传递到 ajax/javascript

how to pass variable from html to ajax/javascript

我有以下 HTML 页面,我在成功验证后进入了该页面。在它的主体中,我得到 access_token 值。

<html>
<head>
    <title>Authorization successful</title>
</head>
<body>
    <p>Welcome. You are authorized to access the page.</p>     
    <p>access_token: {{ access_token }}</p>
    <p>token_type:   {{ token_type }}</p>
    
    <form method="POST" action="/protected_hi" >                   
        <button type="submit" id="protectedApiButton">Protected API</button>
    </form>
    <script src="ajax.js"></script>
</body>
</html>

该页面有一个名为“Protected API”的按钮,它在该按钮上注册了 ajax.js 脚本。 如何在我的 ajax.js 脚本中获取 access_token 变量的值?

let protectedApiButton = document.getElementById('protectedApiButton');
protectedApiButton.addEventListener('click', buttonClickHandler)

function buttonClickHandler() {
    
    var myAttribute = <------------- how to assign access_token value from html template to here?
    console.log(myAttribute);

    
    const xhr = new XMLHttpRequest();   
    xhr.open('POST', 'http://dummy.restapiexample.com/api/v1/create', false);
    xhr.setRequestHeader('Content-type', 'application/json');


    
    xhr.onprogress = function(){
        console.log('On progress');
    }

    
    xhr.onload = function () {
        if(this.status === 200){

            console.log(this.responseText)
        }
        else{
            console.log("Some error occurred")
        }
    }   
    params = `{"name":"ravi","age":"43"}`;          
    xhr.send(params);    
}

添加隐藏类型的输入来存储访问令牌。

<input type="hidden" id="access_token" value="token-goes-here" />

然后从 access_token 中检索值 buttonClickHandler():

function buttonClickHandler() {
  var myAttribute = document.getElementById('access_token').value;
  ...
}