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

时间:2018-11-26 13:13:46

标签: javascript jquery api linkedin

更新: 我没有提到我已经读过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(在索引标题中):

<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)。

1 个答案:

答案 0 :(得分:4)

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

  

使用setRequestHeader()时,必须在调用open()之后调用它,   但在调用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; });