1. webservice代码如下:
注意,必须加入[System.Web.Script.Services.ScriptService]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
/// <summary>
///WebService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
public WebService () {
//如果使用设计的组件,请取消注释以下行
//InitializeComponent();
}
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
[WebMethod]
public string GetTrafficLight()
{
return "{1:{lon:'104.58',lat:'30.66'},2:{lon:'105.58',lat:'31.66'}}";
}
}
2. ajax代码如下:
$("input[id$='btn_id_drawtraficlight']").click(function() {
try {
$.ajax({
type: "POST", //访问WebService使用Post方式请求
contentType: "application/json", //"application/json", //WebService 会返回Json类型
url: "../WebService.asmx/GetTrafficLight", //调用WebService的地址和方法名称组合 ---- WsURL/方法名
data: "{}", // {value1:'心想事成'} 这里是要传递的参数,格式为 data: "{paraName:paraValue}",下面将会看到
dataType: 'json',
success: function(result) { //回调函数,result,返回值
// var tlist = eval("(" + result + ")"); // jquery 已经转为json了,所以不要这句话,不然会报:missing ] after element list的错误
var tlist = eval("(" + result.d + ")");//jquery转为json,d对象的值为字符串,需要转换为jison,注意[ {},{}]才有length属性,{id:{},id:{}},是纯对象,没有length属性
if (tlist) {
for(var i in tlist)
{
for (var j in tlist[i]) {
alert("id:"+i+"=>"+j+":"+tlist[i][j]);
}
}
}
}
});
} catch (e) {
alert("draw trafic light error:\n" + e.name + ":" + e.message)
}
});
3. 注意url 是 相对于js的目录