【问题标题】:Titanium: get html source codeTitanium:获取 html 源代码
【发布时间】:2015-03-12 13:01:44
【问题描述】:

我正在 Titanium 中制作一个应用程序,我希望在其中从 URL 获取 HTML 源代码并将其作为字符串返回。我已尝试执行以下操作:

function getHTML(URL) {
  var client = Ti.Network.createHTTPClient({
      onload: function(){
          Ti.API.info("Received HTML!");
          return this.responseText;
      },
      onerror: function(e){
        Ti.API.debug(e.error);
        alert('Internetconnection failed. Try again later.');
      },
      timeout : 5000
  });
  client.open("GET", URL);
  client.send();
}

但是,当我运行此代码时,该函数似乎没有返回任何内容。 您的帮助将不胜感激。 附言我需要专门的 HTML 源代码,所以使用 JQuery 之类的东西对我没有帮助。

【问题讨论】:

    标签: html titanium


    【解决方案1】:

    由于函数onload 是异步的,它确实不返回任何内容。您必须使用回调函数才能使其工作

    function getHTML(URL, callback) {
        var client = Ti.Network.createHTTPClient({
        onload: function(){
            Ti.API.info("Received HTML!");
            if (callback){
                 callback(this.responseText);
            }
        },
        onerror: function(e){
            Ti.API.debug(e.error);
            alert('Internetconnection failed. Try again later.');
        },
        timeout : 5000
        });
        client.open("GET", URL);
        client.send();
    }
    

    所以要调用它,请执行以下操作:

    getHTML('http://google.com', function(html){
         console.log('got html!', html);
    });
    

    【讨论】:

    • 我这样做了,但 html 仍然未定义。
    猜你喜欢
    • 2013-04-06
    • 2011-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多