聲明,解決方案由網上收集而來,個人整理。有別人的,也有我的。
一、webserive端
1.web.config
需要在web.config的configuration節點中加入如下的黑體部分內容。
<system.web>
<webServices>
<protocols>
<add name="HttpGet" />
<add name="HttpPost" />
</protocols>
</webServices>
</system.web>
再加入以下內容
<system.webServer>
<!--解決跨域請求 by wys -->
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET" />
<add name="Access-Control-Allow-Headers" value="x-requested-with,content-type" />
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
2.asm.x
還不清楚是否必須在類前要加上以下內容。沒時間測
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
3.一個方法
[WebMethod]
public string getProduct()
{
DataTable dt = BizLogic.ProductsBLL.GetProductInfo();
HttpContext.Current.Response.ContentType = "application/json";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
var obj = new
{
Status = 1,
Data = dt
};
return Newtonsoft.Json.JsonConvert.SerializeObject(obj);
}
二。JS部分
var svr_url = "http://192.168.2.23:9001/******.asmx/";
function getdata(action,para,callback)
{
var uu = svr_url + action;
$.ajax({
type: "post",
contentType:"application/json",
data:para,
url:svr_url + action,
dataType:'json',
success:function(result){
console.log(result);
var res=JSON.parse(result.d);
if(res.Status==1){
if(callback)callback(res.data);
}
else
{
alert(res.Message);
}
},
error:function(err){
console.log(err);
}
});
}
三。HTML頁面
getdata('getProduct',[],afterGet);
var afterGet=function(data)
{
......
}
以上實測通過,系統運行中。