asp.net 使用jQuery ajax 调用后台方法..............................................新手在线求解
<a class="format">123</a><br />
<a class="format">456</a>
<script type="text/javascript">
$(".format").click(function(iFormat) {
$.ajax({
type: "post",
url: "test.aspx/chooseFormat",
data:{"str":iFormat},
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function(data) {
alert(‘’);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
</script>
[WebMethod]
public static void chooseFormat(string str)
{
string aaa = str;
}
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm15.aspx.cs" Inherits="Linq_Test.WebForm15" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//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="jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".format").each(function () {
$(this).bind("click", function () {
$.ajax({
type: "post",
url: "http://localhost:4321/test/WebForm15.aspx/GetStr", //项目是虚拟目录我就直接写成这了
data: "{'str':'" + $(this).text() + "'}",
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function (data) {
alert(data.d);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.responseText);
}
});
});
});
});
</script>
</head>
<body>
<a href="#" class="format">content1</a> <a href="#" id="A1" class="format">content2</a>
<a href="#" id="A2" class="format">content3</a> <a href="#" id="A3" class="format">content4</a>
</body>
</html>
[code=csharp]
[WebMethod]
public static string GetStr(string str)
{
return str;
}
$(document).ready(function () {
$(".format").each(function () {
$(this).bind("click", function () {
$.ajax({
type: "post",
url: "test.aspx/chooseFormat",
data: { "str": $(this).text() },
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
});
<a class="format" onclick="submit('123');">123</a><br />
<script type="text/javascript">
function submit(id){
$.ajax({
type: "post",
url: "test.aspx/chooseFormat?id="+id,
data:{"str":iFormat},
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function(data) {
alert(‘’);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
</script>