【问题标题】:jQuery AJAX call to Vanilla JS, what am I missing?jQuery AJAX 调用 Vanilla JS,我错过了什么?
【发布时间】:2018-11-26 13:13:46
【问题描述】:

更新: 我没有提到我已经阅读了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)。

【问题讨论】:

  • 它在错误消息中准确地说明了问题所在,不是吗?
  • @DaveNewton 是的,它说它无法在“XMLHttpRequest”上执行“setRequestHeader”并且需要打开该对象。哪个是需要打开的对象,这是否意味着“httpRequest.open ....”语句中的语法有问题?所以对我来说,这并不是那么明显。
  • @MysterX 我在发布之前阅读了该主题,但没有提及。它没有让我更进一步,因为我没有看到它与我的问题有什么关系。然而,ponury-kostek 确实设法简单地解释了它,没有任何混乱,让我理解。所以我不认为它是重复的。
  • ... 需要在setRequestHeader之前打开。在您尝试调用setRequestHeader 后打开它。
  • 嗯,好的。我想我读到它并认为“哦,它必须被打开”(“对象的状态必须是打开的”),我还没有打电话给open

标签: javascript jquery api linkedin


【解决方案1】:

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

【讨论】:

  • 太棒了!我没有看到建议的重复线程如何应用于我的示例,但您的解释简短、准确且中肯,现在看起来非常明显,因此我也记得它。如果可能的话,我会给你更多的支持!
猜你喜欢
  • 2020-09-02
  • 1970-01-01
  • 2022-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-09
  • 2013-07-06
  • 2011-05-13
相关资源
最近更新 更多