App_Code目录下放置WebService.cs文件,文件内容如:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.ServiceModel.Web;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI.WebControls; [WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService] public class WebService : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public void GetStores(string deliveryStartTime, string deliveryEndTime, bool is20To22 = false, string cityPOSCodePrefix = "")
{
var storeListJson = new StringBuilder(); //
var storeList = GetStoreList(deliveryStartTime, deliveryEndTime, is20To22, cityPOSCodePrefix);
storeListJson.Append("[");
foreach (var store in storeList)
{
string format = "{{\"Value\":\"{0}\", \"Text\":\"{1}\"}}"; storeListJson.Append(string.Format(format, store.Value.ToString(), store.Text.ToString()));
storeListJson.Append(",");
}
storeListJson.Remove(storeListJson.Length - , );
storeListJson.Append("]");
// Context.Response.Clear();
Context.Response.ContentType = "text/json; charset=utf-8";
//Context.Response.AddHeader("content-disposition", "attachment; filename=export.json");
//Context.Response.AddHeader("content-length", storeListJson.Length.ToString());
Context.Response.Flush();
Context.Response.Write(storeListJson);
}
}
WebService.asmx文件可以放在网站跟目录下,跟目录下的页面请求WebService拿json数据时:
var url = "/webservice.asmx/GetStores?cityPOSCodePrefix=" + cityPOSCodePrefix + "&deliveryStartTime=" + deliveryStartTime
+ "&deliveryEndTime=" + deliveryEndTime + "&is20To22=" + is20To22;
js对请求返回的数据进行处理,如下:
$.ajax({
url: url,
type: 'get',
async: false,
contentType: 'text/json; charset=utf-8',
success: function (result) {
//alert(result.d[0]);
var storeListString = "";
var storeLiValueStart = "<li style=\"float: left; margin-left: 40px; margin-top: 8px; width: 120px; border-radius: 8px; background-color: #FFF; border: 2px solid rgb(0,119,175);color:#0077af; padding: 4px 0px; text-align: center; cursor: pointer\" id=\"";
var storeLiValueEndAndTextStart = "\">";
var storeLiTextEnd = "</li>"; for (var i = ; i < result.length; i++) {
storeListString += storeLiValueStart;
storeListString += result[i].Value;
storeListString += storeLiValueEndAndTextStart;
storeListString += result[i].Text;
storeListString += storeLiTextEnd;
} $("#storeListTest").html(storeListString);
}
注意:要想拿到返回的json数据,web.config文件中system.web节点下必须加如下节点:
<webServices>
<protocols>
<add name="HttpGet" />
</protocols>
</webServices>