代码之家  ›  专栏  ›  技术社区  ›  Martin

jquery如何从HTML响应中获取正文内容

  •  1
  • Martin  · 技术社区  · 14 年前

    我有点问题。

    我有一个Ajax请求,它被发送出去进行数据库更新。然后返回如下响应:

    ...
    ...
    </head>
    <body class="contentpane">
    {"id":"27","votes":14,"sum":45,"avg":"3.2"}
    </body>
    </html>
    

    如何获取body类“contentpane”的内容,然后将其转换为JSON对象?

    我的请求函数如下:

      jQuery.post("index.php?option=com_ttvideo&task=savevote&tmpl=component", {rate: value, id: <?php echo $this->video->id; ?> }, function(html)
      {
        // get contents of "contentpane" from response html
        // convert to JSON object e.g.
        // var rating = jQuery.parseJSON(content_of_body);    
        // is the above JSON parse correct?    
    
        // Select stars to match "Average" value
        ui.select(Math.round(rating.avg));
    
        // Update other text controls...
        jQuery("#avg").text(rating.avg);
        jQuery("#votes").text(rating.votes);
    
        // Show Stars
        jQuery("#loader").hide();
        jQuery("#rat").show();
    
      });
    
    2 回复  |  直到 12 年前
        1
  •  1
  •   SLaks    14 年前

    这样地:

    $.parseJSON($('body', html).text())
    

    我假设,也许是错误的,JSON将被HTML转义。如果不是,你有时可以打电话 .html() 而不是 .text() ,但更可能需要编写自己的分析器。

    您应该用一个真正的JSON响应替换您的WebService。

        2
  •  4
  •   user1709374    12 年前

    相当容易。按DIV包裹车身内部:

    $.get(url, {}, function(data){
      var data = data.replace('<body', '<body><div id="body"').replace('</body>','</div></body>');
      var body = $(data).filter('#body');
      (... do what you want with body ...)
    });