【问题标题】:jquery returning null - why?jquery 返回 null - 为什么?
【发布时间】:2010-05-12 13:28:39
【问题描述】:

我正在使用 jquery ajax $.get,它在我的服务器上调用一个 php 脚本并从另一个站点(域)检索内容。它返回完整的网页。然后我想使用 .find() 方法从“中心”标签中提取 html 数据,但我遇到了一些问题。

$("#btnGetData").click(function(){
  $.get("pgiproxy.php",{ data: $("#formdata").serialize() },
    function(result) {

      alert($(result).find('center').html()); 

      val = $(result).find('center').html();
      alert(val);

      $('#BFX').html(result);
      alert( $('#BFX').find('center').html() );  

    });
});

前 2 个方法都返回“null”,但是当我将 ('result') html 插入 #BFX div 时,它在我的显示器上正确显示,最终警报正常工作,它 find()s the 'center ' 标记并在警报中显示 html 数据。

在尝试从返回的 ajax 数据“结果”中“查找()”“中心”标签时,任何人都可以看到为什么我返回“空”(如前 2 个警报)。

感谢任何帮助

尼克。

【问题讨论】:

  • 我不习惯jquery,但是result.find('center').html()应该不行?
  • 您是否转储了 'result' 的内容?您可以尝试在回调后设置数据类型 'html' $.get('foo', {}, function(){}, 'html');
  • 嗨 jAndy,我将数据类型设置为 'html',使用 --alert($(result).find('center').html()); 的结果仍然相同; --,返回null。

标签: jquery find


【解决方案1】:

你应该试试这个:

$("#btnGetData").click(function(){
  $.get("pgiproxy.php",{ data: $("#formdata").serialize() },
    function(result) {
      var temp = $('<div/>').html(result);

      alert(temp.find('center').html()); 

      val = temp.find('center').html();
      alert(val);

      $('#BFX').html(result);
      alert( $('#BFX').find('center').html() );  

    });
});

【讨论】:

  • 嗨 vsnyc,是的,这种方法有效。但是为什么我需要在我'find('center').html()'之前先将数据放入'temp'变量中。为什么我不能只做一个步骤方法并直接从“结果”中提取“中心”???尼克。
  • 因为 jQuery 需要遍历一个 DOM 对象或 jQuery 对象,而不是 JSON 对象,或者它的任何响应......我认为它不是 DOM 对象。这是做这些事情时的方法,将响应转换为我们可以处理的元素。
  • 好的,谢谢 vsync。响应来自一个 PHP 脚本,它使用“fopen 和 fgets”来获取网页的内容,我假设它只是作为“文本”返回?是 $('
    ') 在 "" var temp = $('
    ').html(result); "" 只是用作将“结果”转换为可用 jQuery 对象的占位符?
  • 是的,它只是一个占位符,并不是真正存在于 DOM 中的元素。
【解决方案2】:

result 的内容将取决于响应的 MIME 类型,如 here 所述。如果result 只是文本,$() 函数会将其视为选择器。

【讨论】:

  • 嗨语法,这是我的 php 脚本中使用的代码,它返回 jquery ajax 调用的结果: function getPage($pageURL) { // 设置您的返回内容类型 header('Content-type:文本/html; charset=utf-8'); // 获取该网站的内容 $handle = fopen($pageURL, "r"); if ($handle) { while (!feof($handle)) { $buffer = fgets($handle, 4096);回声$缓冲区; } fclose($句柄);我假设结果只是文本???我很高兴将结果放入隐藏的 div 中,然后从“中心”标签中提取数据,但直接这样做会很好。
猜你喜欢
  • 2013-06-11
  • 1970-01-01
  • 2011-04-10
  • 2015-01-02
  • 2022-12-26
  • 2016-12-28
  • 2015-11-25
  • 2015-07-04
  • 2019-09-29
相关资源
最近更新 更多