使用webform、websevice来进行ajax请求操作

通过使用webform(asp.net非mvc) 、webservice 作为请求接口在前台发送ajax请求:
1.前台代码:

 1 $.ajax({
 2     type: "POST",
 3     //方法所在页面和方法名
 4     url: "../ztest.aspx/GetHtmlJson",
 5     //一定要加上,不然服务端默认返回的是text/html ;charset=utf-8 格式的页面
 6     contentType: "application/json; charset=utf-8",
 7     dataType: "json",
 8     //此处一定要注意:一定要是json字符串的形式
 9     data: '{id:' + $("#htmlId").val() + '}',
10     beforeSend: function () {
11             index = layer.load(2);
12         },
13         success: function (data) {
14             //返回的数据用data.d获取内容
15             qjson = JSON.parse(data.d);
16             console.log(qjson);
17 
18         },
19         error: function (err) {
20             console.log(err);
21         }
22 });

2.webform 后台代码:
ps:当后台返回数据中带有base64字符串的时候,反序列化json的时候,可能会报错json字符串超长的错误,此时需要在web.config文件中的configuration 节点下添加配置:

1 <system.web.extensions>
2 <scripting>
3 <webServices>
4 <jsonSerialization maxJsonLength="1024000000" />
5 </webServices>
6 </scripting>
7 </system.web.extensions>
 1 [WebMethod]//加上注解,使用静态方法
 2 public static string GetHtmlJson(int id)
 3 {
 4 //id = Convert.ToInt32();
 5 string htmlJson = string.Empty;
 6 if (id <= 0)
 7 {
 8 htmlJson = "";
 9 }
10 else
11 {
12 htmlJson = new BLL.BLL_CommonWrongTopic().GetHtmlJson(id);
13 }
14 
15 return htmlJson;
16 }

猜你喜欢

转载自www.cnblogs.com/wangyuliang/p/10962743.html
今日推荐