jQuery AJAX - Returned HTML vanishes
I'm mucking about with jQuery AJAX and have stumbled upon an oddity (or rather a lack of understanding on my part :). Here is the code for my main ASPX page:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="jQuery_Test.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transi开发者_StackOverflow社区tional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#btnGo').click(function() {
$.ajax({
type: "GET",
url: 'GetValues.aspx',
contentType: 'text/html',
success: function (html) { $("#Yo").append(html); }
});
})
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<p id="Yo">Yo there!</p>
<br />
<a href="#" class="yo">Yo there!</a>
<br />
<a href="#">I'm in a DIV!</a>
<br />
<button id="btnGo">Go</button>
</div>
<br />
<br />
<a href="#">I'm not in a DIV!</a>
</form>
</body>
</html>
and here is the codebehind of the 'GetValues.aspx' page:
using System;
namespace jQuery_Test
{
public partial class GetValues : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "text/html";
Response.Write("<a href='#'>Hello World</a>");
Response.End();
}
}
}
All I'm doing is, when the 'Go' button is clicked on the main page, I want the anchor tag placed next to a paragraph.
The code does actually work, however, the anchor 'Hello World' appears for about 1 second and then vanishes. Can somebody point out what I'm doing wrong? I'm using jQuery-1.3.2.mins.js which came with VS 2010 Ultimate.
Cheers. Jas.
make your function return false;
$(document).ready(function () {
$('#btnGo').click(function() {
$.ajax({
type: "GET",
url: 'GetValues.aspx',
contentType: 'text/html',
success: function (html) { $("#Yo").append(html); }
});
return false;
})
});
Once your handler code gets run, the button goes ahead and performs its normal function (posting to the page). If you return false at the end of your handler, the event will not bubble and the button will not post.
精彩评论