2

Here's the the form the Ajax code I am testing.

$('body').on('submit','#sign-in', function(e) {
    e.preventDefault();

    var data = $(this).serialize();

    var url = $(this).attr('action');
    $.ajax({
        //this is the php file that processes the data and send mail
        url : url,
        type : "POST",
        data : data,
        dataType:"html",
        //Do not cache the page
        cache : false,
        //success
        success : function(response,status) {
            console.log($(response).filter('#dashboard'));
            console.log($(response).find('#dashboard').html());
        }
    });
});

Here is the response.

<!DOCTYPE html>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<body>
    <div id = "dashboard">
        <div id = "dash2">
        <h1>HELLO</h1>
        </div>
    </div>
</body>
</html>

Based from the code above upon, success jQuery filter was able to fetch the div with an id #dashboard however find return me an undefined.

Why is it working like that?

For your information, I am using JQuery 1.9

UPDATE

Using the suggestion of Bergi, I have removed the html,body and head tag of the returned html and this is the error I received.

Uncaught Error: Syntax error, unrecognized expression:

HELLO

HELLO FITCCHHH jquery-1.9.0.min.js:2

4

3 に答える 3

4

jQuery はページ全体innerHTMLを aとして設定する<div>ため、doctype、html、head および body 要素は解析されません。結果の要素のコレクションのみが返されます。 yourはこれらのトップレベル要素の 1 つであるため、の代わりに#dashboard必要です。filterfind

以下も参照してください。

これを解決する方法がわかりません。明らかに、そこにはjQueryの癖がたくさんあります。私が考えることができるもの:

  • jQuery.parseXMLを試す
  • filter問題の要素を jQuery コレクションから取得することに依存します。ただし、ブラウザは解析の内容について一貫していないように見えるため、次のようにする必要があります $response[$response.is("#dashboard") ? "filter" : "find"]("#dashboard")
  • 不正なコレクションをいくつかの要素に追加しfind、そこから:$("<div/>").html(response).find("#dashboard")
  • を待つjQuery.parseHTML
  • HTMLドキュメント全体を送信するのではなく、#dashboard関心のある要素のみをhtml文字列として送信します
于 2013-02-03T13:22:36.867 に答える
1

上記のように parseHTML を使用する必要があります。filter と find の違いは、返された HTML スニペット内の要素の場所にあるようです。#foo を探している場合、返された HTML の最上位要素が #foo の場合は .filter('#foo') を使用し、それ以外の場合は .find('#foo') を使用します。

于 2014-03-19T16:31:55.587 に答える