简体   繁体   English

在AJAX响应数据上使用jQuery

[英]Using jQuery on AJAX response data

I'm looking to use jQuery to determine if the current page has changed upstream, and if so, perform some action. 我正在寻找使用jQuery来确定当前页面是否已在上游更改,如果有,请执行一些操作。

I want to do this by using jQuery selectors over the data returned by an AJAX call (for the purposes of this question, my "page has changed" metric will be "has the content of first <h1> changed"). 我想通过对AJAX调用返回的数据使用jQuery选择器来实现此目的(出于此问题的目的,我的“页面已更改”指标将为“第一个<h1>的内容已更改”)。

Thus I find myself wanting to use jQuery selectors over the HTML returned by an AJAX get() . 因此,我发现自己想在AJAX get()返回的HTML上使用jQuery选择器。 The "best" "solution" I've found thus far is appending the data to some hidden div, and using a selector over that, as below: 到目前为止,我发现的“最佳”“解决方案”是将数据附加到某个隐藏的div,并在其上使用选择器,如下所示:

var old_title = $('h1').html();

$.get(url, function(data) {
    $('#hidden_temporary_storage').append(data);
    var new_title = $('#hidden_temporary_storage h1').html();
    if (new_title !== old_title) {
        do_something();
    }
});

This feels so very wrong - I'd be nesting html / head / body tags, and there would be id collisions et cetera. 这感觉非常错误-我将嵌套html / head / body标签,并且会有id冲突等等。

I have no control over the upstream page, so I can't just "get the data in a more convenient format" alas. 我无法控制上游页面,所以我不能只是“以更方便的格式获取数据”。

You can do: 你可以做:

var x = $('<div>'+data+'</div>').find('h1').html();
// use x as you like

ie you don't need to append the returned data to your page to be able to get properties and values from HTML elements defined within it. 也就是说,您无需返回的数据附加到页面即可从其中定义的HTML元素获取属性和值。 This way there would be no id collisions, multiple head/body tags etc. 这样就不会有ID冲突,多个头部/身体标签等。

I think your best bet here is to use an iFrame. 我认为您最好的选择是使用iFrame。 And then use jQuery on the content of that iFrame. 然后在该iFrame的内容上使用jQuery。

var old_title = $('h1').html();

$.get(url, function(data) {
    $('<iframe id="tmpContent"></iframe>').appendTo("html");
    $('#tmpContent').contents().find('html').html(data);
    var new_title = $('#tmpContent').contents().find('h1').html();
    if (new_title !== old_title) {
        do_something();
    }
    $('#tmpContent').remove();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM