1

这是我的 $.ajax 函数:

$("div#eventBox").click(function () {
    $.ajax({
        url: "/AJAX Pages/Test.cshtml",
        async: true,
        type: "GET",
        success: function (response) {
            $("div#eventBox").html($(response).find("#bodyP").text());
        },
        error: function (jqXHR, textStatus, error) {
            alert("The AJAX function didn't work.");
        }
    });
});

问题在这里(取自上面的片段):

$("div#eventBox").html($(response).find("#bodyP").text());

但根据此处找到的解决方案:

检索 ajax 响应的特定部分并将其放入变量中

和这里;

使用 jQuery 的 .post() 方法仅选择 HTML 页面的一部分?

我的代码应该可以工作。

我在 JavaScript 控制台中得到的错误是(这也将显示目标 ajax 页面的 html):

Uncaught Error: Syntax error, unrecognized expression: <div id="eventPageWrapper" style="margin: auto; text-align: center; width: 100%;">
    <span style="text-align: center; margin: 5px 10px;">Harlem Ambassadors-Basketball Fundraiser for American Red Cross</span></br>
    <p id="bodyP" style="text-align: center; margin: 5px 10px;">
        The Harlem Ambassadors Basketball team will be in Okmulgee today for a fundraiser for the American Red Cross. It will be held at the Brock Gymnasium and starts at 4:00 p.m. Tickets are on sale now and can be purchased through the American Red Cross. Advanced tickets are $8.00 per student and $10.00 per adult. If the tickets are purchased at the door, they are $10.00 per student and $12.00 per adult. Contact the American Red Cross for tickets or more information at (918)-756-0966 or (918)-932-7323.
    </p>
</div> 

这可能是一个简单的解决方案,但我无法弄清楚我做错了什么。

更新

我找到了空白的来源,使用简单的 html 注释很容易消除。

@{
    Layout = "";
}<!--  HERE WAS WHERE ALL THE WHITE SPACE WAS COMING FROM BEFORE I ADDED THIS COMMENT
--><div id="eventPageWrapper" style="margin: auto; text-align: center; width: 100%;">
    <span style="text-align: center; margin: 5px 10px;">Harlem Ambassadors-Basketball Fundraiser for American Red Cross</span></br>
    <p id="bodyP" style="text-align: center; margin: 5px 10px;">
        The Harlem Ambassadors Basketball team will be in Okmulgee today for a fundraiser for the American Red Cross. It will be held at the Brock Gymnasium and starts at 4:00 p.m. Tickets are on sale now and can be purchased through the American Red Cross. Advanced tickets are $8.00 per student and $10.00 per adult. If the tickets are purchased at the door, they are $10.00 per student and $12.00 per adult. Contact the American Red Cross for tickets or more information at (918)-756-0966 or (918)-932-7323.
    </p>
</div>
4

1 回答 1

2

Do it this way instead:

$("#eventBox").html( $("<div>").html(response).find("#bodyP").text() );

the $() method can't accept html strings that don't start with <

also fixed your eventBox selector.

于 2013-05-17T15:50:08.120 回答