javascript - jQuery AJAX 调用 Vanilla JS,我错过了什么?

标签 javascript jquery api linkedin-api

更新: 我没有提及我已经阅读了 suggested duplicate answer它并没有让我更进一步,因为我不明白它与我的问题有什么关系。不过,下面的用户 ponury-kostek 确实设法简单地解释了它,没有那么困惑,让我能够理解。所以我不认为它是重复的。

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

我只使用一行 jQuery 就可以完成整个工作,没有任何问题 - 但我不想强制用户加载 jQuery 库!

我将发布我正在尝试转换的 jQuery、迄今为止我拥有的 Vanilla JS 解决方案以及 GitHub 页面上建议的转换“公式”:

我正在尝试转换 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(在索引 header 中):

<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; });

关于javascript - jQuery AJAX 调用 Vanilla JS,我错过了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53481912/

相关文章:

javascript - Highcharts 极坐标 : series appear over others when toggle to visible

c# - AJAX 路径不对

javascript - 如何使用 GET 发送正文请求

api - 2Checkout API - 定期付款是否有与之关联的定期 ID?

Java Spring Boot如何知道客户端收到API的响应

Javascript |如何避免 Date.now() 操作

javascript - 文件上传阻止更大的文件

javascript - 在javascript中保持第二个变量值 "one behind"第一个变量值

javascript - 不支持请求方法 'OPTIONS' - Spring Boot 应用程序

javascript - CORS 在 php slim 框架中不工作