/*
*Webservice的代码
*/
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Web.Script;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
using System.Collections.Generic;
namespace Demo.Webservice
{
/// <summary>
/// WebService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
[ScriptService]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
// [System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
[ScriptMethod]
public SortedDictionary<string, object> save(string name)
{
Context.Response.Cache.SetNoStore();
SortedDictionary<string, object> values = new SortedDictionary<string, object>();
values.Add("message",
string.IsNullOrEmpty(name) ? "无名氏" :
string.Format("你好:{0},{1}", name, DateTime.Now));
return values;
}
}
}
//前台jquery的调用
<!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>
<script src="js/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
<script src="js/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$("#script").click(function() {
$.ajax({
type: "POST",
url: '../Webservice/WebService.asmx/save',
contentType: "application/json;utf-8",
data:"{name:'Wangsx'}",//这里是传递的参数,我这里试过"name='wangsx'",总是会报错,最后我还是改成了Json格式的数据传递
success: function(data) {
var json = eval(data);
alert(json.d.message);
},
failure: function(mes) {
alert(mes);
},
error: function(dd) {
var d = dd;
alert(dd.responseText);
}
});
</script>
</head>
<body>
<input id="script" type="button" value="button" />
</form>
</body>
</html>