【问题标题】:how to pass variable from html to ajax/javascript如何将变量从 html 传递到 ajax/javascript
【发布时间】:2022-02-06 10:54:47
【问题描述】:

我有下面的 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);    
}

【问题讨论】:

    标签: javascript html ajax


    【解决方案1】:

    添加类型为 hidden 的输入以存储访问令牌。

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

    然后在buttonClickHandler()中检索access_token中的值:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-30
      • 1970-01-01
      • 2018-03-23
      • 2016-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多