JQuery AJAX函数没有将新的变量值传递给全局范围

时间:2016-08-30 21:45:06

标签: javascript jquery ajax twitter

下午好,我是编程的新手,并且在向Twitter推文发送javascript / jquery API调用时出现问题。目标是能够点击Tweet按钮并在Tweet中发送页面上显示的当前报价。这是CodePen上的current attempt,下面是Javascript;

var counter = 0;
var $body = $('body'),
redVal = 55,
greenVal = 50,
blueVal = 25,
quote;

var sendText = "something current...";  //this is the variable that should be replaced by the API calls and sent to Twitter


//this is Twitter's function to format the page
window.twttr = (function(d, s, id) {
    var t, js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s);
    js.id = id;
    js.src = "https://platform.twitter.com/widgets.js";
    fjs.parentNode.insertBefore(js, fjs);
    return window.twttr || (t = {
        _e: [],
        ready: function(f) {
            t._e.push(f)
        }
    });
}(document, "script", "twitter-wjs"));

//the actions to call the quote API
function start() {
redVal = (redVal + 45) % 255;
greenVal = (greenVal + 40) % 255;
blueVal = (blueVal + 20) % 255; 
var colorVal = "rgba(" + redVal + "," + greenVal + "," + blueVal + ", 0.4)";
$body.css({"background-color": colorVal });


if (counter % 2 == 0) {
   $.ajax({
       url: "http://quotes.stormconsultancy.co.uk/quotes/random.json?",
       jsonp: "callback",
       dataType: "jsonp",
       data: {
           q: "id, author, quote",
           format: "json"
       },

       success: function( response ) {
           var quote = response.quote;
           var author = response.author;
           document.getElementById("textDisplay").innerHTML = quote;
           document.getElementById("author").innerHTML = author;
           passText(quote);
       }
    }); 
   counter += 1; 
} else {     $.ajax({
       url: "http://api.icndb.com/jokes/random?",
       jsonp: "callback",
       dataType: "jsonp",
       success: function( response ) {
           var quote = response.value.joke;
           var author = " ";
           document.getElementById("textDisplay").innerHTML = quote;
           document.getElementById("author").innerHTML = author;
           passText(quote);
       }
    }); 
   counter += 1;
}
}

//my attempted helper function to pass the quote values
function passText(superT) {
    console.log(superT);
    sendText = superT;
    return sendText;
    }

//the API call to Twitter to send the Tweet 
twttr.ready(function (twttr) {
    twttr.events.bind('tweet', 
        twttr.widgets.createShareButton(
        'https://dev.twitter.com/',
        document.getElementById('container'),
        {
        text: sendText }
        ));
})

我认为问题在于,jQuery AJAX脚本中执行的API调用不会被识别为以jQuery AJAX调用之外可访问的方式重新分配给quote变量。我阅读了其他建议(example)来尝试从全局范围分配引用变量,或者通过辅助函数(example传递值,如上所述...),但两者都只是最初发送值在没有JQuery值的情况下分配给Twitter API的quote变量。

我希望有一些简单的东西,我不知道会让这个工作。如果它不是变量范围的问题,或者有更好的方法来处理这个比JQuery AJAX函数我会感激任何建议。感谢您的时间和任何帮助。

0 个答案:

没有答案