前台代碼如下 :
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<!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>AJAX</title>
<script type="text/javascript" src="Scripts/jquery-1.4.1-vsdoc.js"></script>
<script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
<script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btnShow").click(function () {
$.ajax(
{
type: "POST", //访问WebService使用Post方式请求
contentType: "application/json",
url: "WebForm1.aspx/HellWorld", //调用WebService的地址和方法名称组合 ---- WsURL/方法名
data: "{str:'dddddddddddddddddd'}", //这里是要传递的参数,格式为 data: "{paraName:paraValue}",下面将会看到
dataType: 'json', //WebService 会返回Json类型
success: function (data) { //回调函数,result,返回值
alert(data.d);
},
error: function (error) {
alert("error")
}
}
);
})
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" value="hello" id="btnShow" />
</div>
</form>
</body>
</html>
後台代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]//必須加上這個東西
public static string HellWorld(string str)
{
return str;
}
}
}