$.ajax({
url: url, (此url表示后台提供的API接口)
type: 'GET', (请求的方式,除此之外还有post)
dataType: 'jsonp', (jsonp表示为跨域请求)
success: function(data) {
console.log(data);
},
error: function(data){
console.log(data);
}
});
JavaScript调用WebService方法(xmlhttp+webservice)
function RequestByGet(data){
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");//Webservice location.
var URL="http://localhost:1323/WebSite6/Service.asmx/SayHelloTo?Name=Zach";
xmlhttp.Open("GET",URL, false);
xmlhttp.SetRequestHeader ("Content-Type","text/xml; charset=utf-8"); (设置请求头部分)
xmlhttp.SetRequestHeader ("SOAPAction","http://tempuri.org/SayHelloTo");
xmlhttp.Send(data);
var result = xmlhttp.status; //OK(表示status为200)
if(result==200) {
document.write(xmlhttp.responseText);
}
xmlhttp = null;
}
function RequestByPost(value) {
var data;
data = '<?xml version="1.0" encoding="utf-8"?>';
data = data + '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">';
data = data + '<soap:Body>';
data = data + '<SayHelloTo xmlns="http://tempuri.org/">';
data = data + '<Name>'+value+'</Name>';
data = data + '</SayHelloTo>';
data = data + '</soap:Body>';
data = data + '</soap:Envelope>';
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
var URL="http://localhost:1323/WebSite6/Service.asmx";
xmlhttp.Open("POST",URL, false); (post请求)
xmlhttp.SetRequestHeader ("Content-Type","text/xml; charset=gb2312");
xmlhttp.SetRequestHeader ("SOAPAction","http://tempuri.org/SayHelloTo");
xmlhttp.Send(data);
document.write( xmlhttp.responseText);
}
对于上述两种方法都是在浏览器为IE的情况下去写的,如果要用别的浏览器去渲染的话,或者不确定是哪一种浏览器,可以使用下面的语句对对象进行选择判断:
if(window.XMLHttpRequest) {
req = new XMLHttpRequest();
}else if (window.ActiveXObject) {
req = new ActiveXObject(“Microsoft.XMLHTTP”);
}