简介
对于webservice接口跨越访问有前端已有相关解决方案:比如:ajax使用jsonp 或者用专门的jquery.jsonp.js来进行访问。
此处介绍如何通过后台访问接口,然后将返回值提供给前台,此处以MVC编写为例
后台Control中编写
//url是要访问的服务接口地址
public string queryRespose(string url)
{
string json;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 15000;
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
json = reader.ReadToEnd();
reader.Close();
}
catch (Exception ex) { json = ex.Message; }
return json;
}
前端页面调用
$.ajax({
type: "GET",
url: "/ControlName/queryRespose",
dataType: "json",
async: false,
data: {
url: url
},
beforeSend: function () {
},
success: lang.hitch(this, function (msg) {
//dosomething
}),
error: function () {
console.log("error");
}
});