jQuery AJAX 调用 Vanilla JS,我缺少什么?

jQuery AJAX call to Vanilla JS, what am I missing?

更新: 我没有提到我已经阅读了 但它并没有让我进一步了解,因为我没有看看它与我的问题有什么关系。下面的用户 ponury-kostek 确实设法简单地解释了它,没有那么混乱,让我理解。所以这就是我不认为它是重复的原因。

我正在尝试在用户使用 LinkedIn 登录时将用户数据保存到数据库中(以跟踪谁看过我的页面)。我找到了一个使用 jQuery 的教程,我找到了一个 GitHub (here) 页面,用于将 jQuery 转换为 Vanilla JS,但我很难理解我需要做什么来转换这个特定的陈述。

我只使用了一行 jQuery 就完成了整个工作,没问题 - 但我不想强迫用户加载 jQuery 库!

我将 post 我正在尝试转换的 jQuery,我目前拥有的 Vanilla JS 解决方案,以及 GitHub 上建议的转换 "formula" ] 页面:

jQuery 我正在尝试转换:

$.post('saveUserData.php', 
  {
    oauth_provider: 'linkedin',
    userData: JSON.stringify(userData)
  }, 
  function(data){ return true; });

我对 Vanilla JS 解决方案的尝试

var theUrl = 'saveUserData.php';
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function (data) {

};
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.open('POST', theUrl);
httpRequest.send({oauth_provider:'linkedin',userData: JSON.stringify(userData)}, function(data){ return true; });

抛出错误:

script.js:10 Uncaught DOMException: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.
    at saveUserData (http://localhost:8012/linkedCV/script.js:10:14)
    at displayProfileData (http://localhost:8012/linkedCV/index.php:43:4)
    at B.<anonymous> (https://platform.linkedin.com/js/framework?v=1.0.350-1429&lang=undefined:3350:17)
    at B.runHandler (https://platform.linkedin.com/js/framework?v=1.0.350-1429&lang=undefined:172:9)
    at B.<anonymous> (https://platform.linkedin.com/js/framework?v=1.0.350-1429&lang=undefined:3355:6)
    at B.handleSuccessResults (https://platform.linkedin.com/js/framework?v=1.0.350-1429&lang=undefined:172:9)
    at Object.g [as success] (https://platform.linkedin.com/js/framework?v=1.0.350-1429&lang=undefined:3243:4)
    at Object.incoming (https://platform.linkedin.com/js/framework?v=1.0.350-1429&lang=undefined:817:38)
    at _window_onMessage (https://platform.linkedin.com/js/framework?v=1.0.350-1429&lang=undefined:581:102)

我的JS(在索引头):

<script type="text/javascript" src="//platform.linkedin.com/in.js">
    api_key: thecorrectAPIkey aka 'Client ID'
    authorize: true
    onLoad: onLinkedInLoad
    scope: r_basicprofile r_emailaddress
</script>

<script type="text/javascript">
    // Setup an event listener to make an API call once auth is complete
    function onLinkedInLoad() {
        IN.Event.on(IN, "auth", getProfileData);
    }

    // Use the API call wrapper to request the member's profile data
    function getProfileData() {
        IN.API.Profile("me").fields("id", "first-name", "last-name", "headline", "location", "picture-url", "public-profile-url", "email-address").result(displayProfileData).error(onError);
    }

    // Handle the successful return from the API call
    function displayProfileData(data){
        var user = data.values[0];
        document.getElementById("picture").innerHTML = '<img src="'+user.pictureUrl+'" />';
        document.getElementById("name").innerHTML = user.firstName+' '+user.lastName;
        document.getElementById("intro").innerHTML = user.headline;
        document.getElementById("email").innerHTML = user.emailAddress;
        document.getElementById("location").innerHTML = user.location.name;
        document.getElementById("link").innerHTML = '<a href="'+user.publicProfileUrl+'" target="_blank">Visit profile</a>';
        document.getElementById('profileData').style.display = 'block';
        saveUserData(user);
    }

    // Handle an error response from the API call
    function onError(error) {
        console.log(error);
    }

    // Destroy the session of linkedin
    function logout(){
        IN.User.logout(removeProfileData);
    }

    // Remove profile data from page
    function removeProfileData(){
        document.getElementById('profileData').remove();
    }
</script>

GitHub转换建议:

// jQuery
$.post('//example.com', { username: username }, function (data) {
  // code
})

// Vanilla
var httpRequest = new XMLHttpRequest()
httpRequest.onreadystatechange = function (data) {
  // code
}
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
httpRequest.open('POST', url)
httpRequest.send('username=' + encodeURIComponent(username))

因为只要我使用建议的 jQuery(我想转换为 Vanilla JS),它就可以完美运行,所以一切正常。因此,我假设不需要页面的其余代码(用于数据库连接和将用户数据保存到数据库的 PHP)。

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader

When using setRequestHeader(), you must call it after calling open(), but before calling send().

var theUrl = 'saveUserData.php';
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function (data) {

};
httpRequest.open('POST', theUrl);
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send({oauth_provider:'linkedin',userData: JSON.stringify(userData)}, function(data){ return true; });