ajax 跨域调用webservice 使用jsonp解决方法

 

前端 :

$.ajax({
type: "POST", //访问WebService使用Post方式请求
contentType: "application/json;charset=utf-8", //WebService 会返回Json类型
url: "http://localhost:42072/WebService/Service.asmx/HelloWorld?jsonpcallback=?", //调用WebService
data: "{}",
dataType: 'jsonp',
success: function(response) { //回调函数,result,返回值

//var json = eval('(' + response+ ')');
alert(response.name);

}
});

 

后端:

[WebMethod]
public void HelloWorld()
{
Context.Response.ClearHeaders();

Context.Response.Charset = "UTF-8";

Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
JavaScriptSerializer js = new JavaScriptSerializer();
string jsonpCallback = HttpContext.Current.Request.QueryString["jsonpcallback"];
person p = new person();
p.name = "Hello World";
string jsonStr = js.Serialize(p);

jsonStr= jsonpCallback + "(" + jsonStr + ")";

Context.Response.Write(jsonStr);

Context.Response.End();

}
class person
{
public string name;
}

posted @ 2018-04-13 14:30  我的女人是捡的  阅读(171)  评论(0编辑  收藏  举报