1

我是 sencha touch 2 的新手。我无法设置我的 qrCodeHtml 变量并在 JsonP 请求之外使用它。我知道除了能够设置 qrCodeHtml 变量之外,所有这些代码都有效。请帮我完成这个:

    onMyProfileCommand: function () {
    var api_username = "o_xxxxx";
    var api_key = "R_xxxxxxxxxx";
    var long_url = "http://google.com";
    var qrCodeHtml = '';

    Ext.data.JsonP.request({
        url: 'https://api-ssl.bitly.com/v3/shorten',
        callbackKey: 'callback',
        params: {
            login: api_username,
            apiKey: api_key,
            longUrl: long_url
        },
        success: function (result, request) {
            var shortUrl = result.data.url;
            qrCodeHtml = '<div style="font-size:15px; margin-bottom:5px;">Friends can scan this to <a href="' + shortUrl +
                             '" style="color:inherit; text-decoration:none; font-weight:bold;">view your profile!</a></div><img src="' +
                             shortUrl + '.qrcode" style="height:110px; width:110px;" />';
        }
    });

    this.getLblQrCodeHtml().setData({ QrCodeHtml: qrCodeHtml });
    Ext.Viewport.animateActiveItem(this.getProfileView(), this.slideLeftTransition);
}
4

2 回答 2

1

谢谢 Goyuix,正是我所需要的!这是解决方案:

    onMyProfileCommand: function () {
var api_username = "o_xxxxx";
var api_key = "R_xxxxxxxxxx";
var long_url = "http://google.com";
var controller = this;

Ext.data.JsonP.request({
    url: 'https://api-ssl.bitly.com/v3/shorten',
    callbackKey: 'callback',
    params: {
        login: api_username,
        apiKey: api_key,
        longUrl: long_url
    },
    success: function (result, request) {
        var shortUrl = result.data.url;
        var qrCodeHtml = '<div style="font-size:15px; margin-bottom:5px;">Friends can scan this to <a href="' + shortUrl +
                         '" style="color:inherit; text-decoration:none; font-weight:bold;">view your profile!</a></div><img src="' +
                         shortUrl + '.qrcode" style="height:110px; width:110px;" />';

        controller.getLblQrCodeHtml().setData({ QrCodeHtml: qrCodeHtml });
    }
});

Ext.Viewport.animateActiveItem(controller.getProfileView(), this.slideLeftTransition);

}

于 2012-12-10T14:44:55.130 回答
0

JsonP 请求将异步发出 - 也许您只需将最后两个语句移动到成功事件处理程序中?否则,请求将排队并发出,最后两行将在 qrCodeHtml 变量设置为您尝试生成的 HTML 之前立即发出。

您需要this从外部函数中捕获变量,以便在成功处理程序中使用,因此在定义其他变量的顶部附近的某个地方:

var that = this;

然后更新您的成功处理程序以在that您的请求返回后使用该变量执行更新:

success: function (result, request) {
  var shortUrl = result.data.url;
  qrCodeHtml = '<div style="font-size:15px; margin-bottom:5px;">Friends can scan this to <a href="' + shortUrl +
                         '" style="color:inherit; text-decoration:none; font-weight:bold;">view your profile!</a></div><img src="' +
                         shortUrl + '.qrcode" style="height:110px; width:110px;" />';
  that.getLblQrCodeHtml().setData({ QrCodeHtml: qrCodeHtml });
  Ext.Viewport.animateActiveItem(this.getProfileView(), this.slideLeftTransition);
    }
});
于 2012-12-08T16:01:36.803 回答