使用loadPageSection.js未定义数据

时间:2017-06-05 14:10:07

标签: javascript jquery ajax

我一直试图将这种情况分类2天并且即将疯狂。请任何人都可以帮助我。我有以下脚本基本上模仿jquery .load()...由于与jquery版本的冲突我无法使用。

/**
 * Loads an HTML document from a URL and retuns an element selected using
 * the 'selector' parameter
 *         Example usage:
 *                 loadPageSection('./myPage.html', '#container', (r, err) => console.log(r, err));
 *
 * @method loadPageSection
 * @param  {String} url
 * @param  {String} selector - A valid CSS selector
 * @param  {Function} callback - To be called with two parameters (response, error)
 * @return {void} - The Element collected from the loaded page.
 */
window.loadPageSection = function loadPageSection(url, selector, callback) {
  if (typeof url !== 'string') {
    throw new Error('Invalid URL: ', url);
  } else if (typeof selector !== 'string') {
    throw new Error('Invalid selector selector: ', selector);
  } else if (typeof callback !== 'function') {
    throw new Error('Callback provided is not a function: ', callback);
  }

  var xhr = new XMLHttpRequest();
  var finished = false;
  xhr.onabort = xhr.onerror = function xhrError() {
    finished = true;
    callback(null, xhr.statusText);
  };

  xhr.onreadystatechange = function xhrStateChange() {
    if (xhr.readyState === 4 && !finished) {
      finished = true;
      var section;
      try {
        section = xhr.responseXML.querySelector(selector);
        callback(section);
      } catch (e) {
        callback(null, e);
      }
    }
  };

  xhr.open('GET', url);
  xhr.responseType = 'document';
  xhr.send();
};

然后我有以下脚本。

$('li.product').each(function(index, el) {
    var _this = $(el);
    var thisProductName = _this.find('.title');
    var thisProductURL = thisProductName.find('> a').attr('href');
    var thisContent = loadPageSection(thisProductURL, '.form-field', (r, err) => console.log(r, err));
    alert(thisContent);
}); 

在控制台日志中,我可以看到它正在循环并检索html。然而,在每一个旁边都是“未定义”,循环警报消息也是如此。我不能为我的生活得到这些html片段出现在日志以外的任何地方。我哪里错了?附:我是javascript / jquery的新手。

感谢您的帮助。

0 个答案:

没有答案