ajax跨域调用c# webserver 返回json数据的几点疑惑
站点A c# webserver 代码
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json,XmlSerializeString = false)]
public void Login(string userName, string userPwd, string macAddress)
{
var response = HttpContext.Current.Response;
response.ContentType = "text/json";
var ws = ValitateLogin(userName, userPwd, macAddress);
var json = new JSONHelper {success = true};
json.AddItem("UnReadEmailNum", ws.UnReadEmailNum.ToString());
json.AddItem("IsValid", ws.IsValid.ToString());
json.AddItem("RetString", ws.RetString);
json.AddItem("EmailUrl",ws.EmailUrl);
json.ItemOk();
response.Write(json.ToString());
}
站点B ajax 跨域调用代码
$(function () {
$("#jsonp_btn").click(function () {
$.ajax({
async:false,
url: 'http://192.168.1.2:14671/OA/Email.asmx/Login', // 跨域URL
type: 'GET',
dataType: 'jsonp',
contentType: "application/json; charset=utf-8",
jsonp: 'jsoncallback', //默认callback
data: {"userName":"admin","userPwd":"123456","macAddress":""}, //请求数据
timeout: 5000,
beforeSend: function(){
//jsonp 方式此方法不被触发。原因可能是dataType如果指定为jsonp的话,就已经不是ajax事件了
},
success: function(json) {
//客户端jquery预先定义好的callback函数,成功获取跨域服务器上的json数据后,会动态执行这个callback函数
alert(json.respond);
if(json.actionErrors.length!=0)
{
alert(json.actionErrors);
}
},
complete: function(XMLHttpRequest, textStatus){
alert(textStatus);
},
error: function(xhr){
//jsonp 方式此方法不被触发
//请求出错处理
alert("请求出错(请检查相关度网络状况.)");
}
});
});
});
IE浏览器报:缺少":" 谷歌浏览器报:Uncaught SyntaxError: Unexpected token : 调式查看返回数据为 :
{"UnReadEmailNum":"5","IsValid":"1","RetString":"登录成功","EmailUrl":"http://localhost:14671/OA/login.aspx?id=2"}?
我想知道为什么会报错!!!!
感谢各大侠百忙中浏览小弟的提问 谢谢了。
[解决办法]
jsonp 应该是返回 script block , 例如: callback({"UnReadEmailNum":"5","IsValid":"1","RetString":"登录成功","EmailUrl":"http://localhost:14671/OA/login.aspx?id=2"}?)
wiki: http://en.wikipedia.org/wiki/JSONP