在本地頁面使用$.ajax進行跨域訪問webservice接口:
第一例:
$.ajax({
type: 'GET',
url: 'http://www.pm25.in/api/querys/aqi_details.json?city=wenzhou&token=',
dataType: 'jsonp',
success: function(msg){
alert(JSON.stringify(msg));
},
error:function(){
alert('error');
}
});
成功輸出響應數據;
第二例:
$.ajax({
type: 'GET',
url: "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getWeatherbyCityName?theCityName=溫州",
dataType: 'jsonp',
success: function(msg){
alert('success');
},
error:function(XMLHttpRequest, textStatus, errorThrown){
alert('error');
}
});
輸出error。但在谷歌瀏覽器的調試界面上可以看到如下界面,
證明響應中已經包含需要的數據。問題分析:dataType: 'jsonp',返回的數據類型爲xml,這可能是造成失敗的原因。但爲什麼響應中會有需要的數據?這些數據怎麼取出來呢?
問題補充:
error的回調函數中,textStatus爲parsererror,errorThrown示意回調函數沒有執行,可以確定爲解析異常。是不是jsonp不可以處理xml數據呢?
既然response中有需要的數據,那麼總該有辦法把他們提取出來吧?到底該怎麼取呢?
<script language="javascript" type="text/javascript">
function jsonpCallback(result) {//這裏是回調方法
alert(result.msg);
$("ws1").remove();//注意回調後如果有可能請執行刪除操作
}
$(function () {
$.fn.getWS({ id: 'ws1', url: 'http://host:prot/ser.asmx/method', Callback: "jsonpCallback" });
});
</script>
//服務器端需要執行的操作示例:
//[WebMethod]
public string method1()
{
string str = "{\"msg\":\"這裏是主要內容\"}";
if (HttpContext.Current.Request["jsonp"] != null)//這裏是執行是否需要返回JSONP字符串的唯一標識
{
HttpRequest Request = HttpContext.Current.Request;
HttpResponse Response = HttpContext.Current.Response;
string callback = Request["jsonp"];
Response.Write(callback + "(" + str + ")");
Response.End();//結束後續的操作,直接返回所需要的字符串
}
return str;
}
(function ($) {
//向目標DOM設置值,常規表單標籤則直接設置Value,Item標籤設置val屬性
$.fn.getWS = function (options) {
var defaults = {
id: "",
url: "",
Callback: ""
}
var options = $.extend(defaults, options);
var oHead = document.getElementsByTagName('HEAD').item(0);
var oScript = document.createElement("script");
oScript.type = "text/javascript";
oScript.setAttribute("id", options.id);
oScript.src = options.url + "?jsonp=" + options.Callback;
oHead.appendChild(oScript);
}
})(jQuery);
一個簡單的調用方法,Jquery原始方法:
$.ajax({
type: "get",
url: "http://localhost:17180/Service1.asmx/method1",
dataType: "jsonp",
jsonp: "jsonp", //傳遞給請求處理程序或頁面的,用以獲得jsonp回調函數名的參數名(默認爲:callback)
jsonpCallback: "jsonpCallback", //自定義的jsonp回調函數名稱,默認爲jQuery自動生成的隨機函數名
contentType: "application/json; charset=utf-8",
success: function (json) {
alert(json.msg);
},
error: function () {
debugger;
alert('fail');
}
});