jQuery.ajax 调用 服务(.aspx,.asmx)

时间:2022-09-26 22:08:50

方法1:Post(json)+IIS下;//aspx,适用本机

        $.ajax({
url: "TpgConnect_Rain/postgreService.aspx/getRainInfo",
type: "POST", //使用Post方式请求
contentType: "application/json;charset=utf-8",
data: "{}", //这里是要传递的参数,格式为 data: "{value1:'心想事成',i:10}"
dataType: "json",
success: function (result) {
datas_rain = JSON.parse(result.d);
alert(datas_rain);
},
error: function (x, e) {
alert("error:" + x.responseText);
}
});

方法2:Get(jsonp);//aspx,可解决跨域  

        $.ajax({
url: "http://10.19.1.54/TpgConnect_Rain/postgreService.aspx/getRainInfo?method=rain",
type: "GET", //使用GET方式请求
dataType: "JSONP",
jsonp: "callback",
data: "{}",
success: function (result) {
datas_rain = JSON.parse(result);
alert(datas_rain);
},
error: function (x, e) {
alert("error:" + x.responseText);
}
});

方法3:XMLHttpRequest;//aspx,传统方式

        var xmlhttp = new XMLHttpRequest();
window.onload = function () {
var url = "http://localhost/TpgConnect/postgreService.aspx?method=rain";
xmlhttp.open("post", url, true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = updatePage;
xmlhttp.send(null);
} function updatePage() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200 || xmlhttp.status == 0) {
alert(eval(xmlhttp.responseText)[0].stationno);
}
else
alert(xmlhttp.status);
}
}

方法4:Post(json)+IIS下;//asmx,适用本机 

        $.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "WebService.asmx/GetWish",
data: "{value1:'心想事成',value2:'万事如意',value3:'牛牛牛',value4:2009}",
dataType: "json",
success: function (json) {
alert("success" + json.d);
},
error: function (x, e) {
alert("error" + x.responseText);
}
});
说明:
1)尽量使用post,无参时:data: "",将返回xml格式;data: "{}",将返回json格式
2)get参数有中文时需要编码,而post不需要
附:
        /* ASP.NET服务源码(aspx)*/
protected void Page_Load(object sender, EventArgs e)
{
Response.AddHeader("Access-Control-Allow-Origin", "*");
string result = "";
var val1 = Request.QueryString["val1"];
var val2 = Request.QueryString["val2"];
var val3 = Request.QueryString["val3"];
var callback = Request.QueryString["method"];
if (callback == "rain")
result = getRainInfo();
else if (callback == "pond")
result = getPondInfo();
else if (callback == "snow")
result = getSnowInfo();
Response.Write(result);
Response.End();
} /* WebService服务源码(asmx) */
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
public WebService()
{
}
[WebMethod]
public string GetWish(string value1, string value2, string value3, int value4)
{
return string.Format("祝您在{3}年里 {0}、{1}、{2}", value1, value2, value3, value4);
}
}