您的位置:首页 > Web前端 > JQuery

利用JQuery jsonp实现Ajax跨域请求 .Net 的*.handler 和 WebService,返回json数据

2015-11-30 16:57 1326 查看
1:跨域请求handler一般处理程序

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
namespace CrossDomain
{
/// <summary>
/// $codebehindclassname$ 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string callbackMethodName = context.Request.Params["jsoncallback"];
string currentCity = context.Request["city"];
currentCity = string.IsNullOrEmpty(currentCity) ? "北京" : "沈阳";
string result = callbackMethodName + "({/"city/":" + "/"" + currentCity + "/", /"dateTime/":" + "/"" + DateTime.Now + "/"});";
context.Response.Write(result);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}


前端页面:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<mce:script type="text/javascript" language="javascript" src="js/jquery-1.4.4.js" mce_src="js/jquery-1.4.4.js"></mce:script>
<mce:script type="text/javascript" language="javascript" src="js/jquery-1.4.4.js" mce_src="js/jquery-1.4.4.js"></mce:script>
<mce:script type="text/javascript" language="javascript"><!--
$(document).ready(function() {
//        var clientUrl = "http://localhost:4508/Handler.ashx?jsoncallback=?";
var clientUrl = "http://192.168.120.179:8086/Handler.ashx?jsoncallback=?"
var currentCity = "哈尔滨";
$.ajax({
url: clientUrl,
dataType: "jsonp",
data : {city : currentCity},
success : OnSuccess,
error : OnError
});
});
function OnSuccess(json) {
$("#data").html("城市:" + json.city + ",时间:" + json.dateTime);
}
function OnError(XMLHttpRequest, textStatus, errorThrown) {
targetDiv = $("#data");
if (errorThrown || textStatus == "error" || textStatus == "parsererror" || textStatus == "notmodified") {
targetDiv.replaceWith("请求数据时发生错误!");
return;
}
if (textStatus == "timeout") {
targetDiv.replaceWith("请求数据超时!");
return;
}
}

// --></mce:script>
</head>
<body>
<div id="data"></div>
</body>
</html>


2:Webservice作为跨域请求的目标:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
namespace CrossDomain
{
/// <summary>
/// $codebehindclassname$ 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string callbackMethodName = context.Request.Params["jsoncallback"];
string currentCity = context.Request["city"];
currentCity = string.IsNullOrEmpty(currentCity) ? "北京" : "沈阳";
string result = callbackMethodName + "({/"city/":" + "/"" + currentCity + "/", /"dateTime/":" + "/"" + DateTime.Now + "/"});";
context.Response.Write(result);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}


页面代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<mce:script type="text/javascript" language="javascript" src="js/jquery-1.4.4.js" mce_src="js/jquery-1.4.4.js"></mce:script>
<mce:script type="text/javascript" language="javascript"><!--
$(document).ready(function() {
//            var clientUrl = "http://localhost:4508/WebService.asmx/HelloWorld?jsoncallback=?";
var clientUrl = "http://192.168.120.179:8086/WebService.asmx/HelloWorld?jsoncallback=?";
var currentCity = "哈尔滨";
$.getJSON(
clientUrl,
{ city: currentCity },
function(json) {
$("#data").html("城市:" + json.city + ",时间:" + json.dateTime);
}
);
});
function OnSuccess(responseData) {
$("#data").html(responseData.city);
}
function OnError(XMLHttpRequest, textStatus, errorThrown) {
targetDiv = $("#data");
if (errorThrown || textStatus == "error" || textStatus == "parsererror" || textStatus == "notmodified") {
targetDiv.replaceWith("请求数据时发生错误!");
return;
}
if (textStatus == "timeout") {
targetDiv.replaceWith("请求数据超时!");
return;
}
}

// --></mce:script>
</head>
<body>
<div id="data"></div>
</body>
</html>


注意配置webconfig:

<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>


JSONP乱码的解决:

后台:

      string result = PublicMethod.DataTableToJson(user);
result = jsonp(callbackMethodName, result);
HttpContext.Current.Response.ContentType = "text/xml; charset=gb2312";
HttpContext.Current.Response.Charset = "gb2312";
HttpContext.Current.Response.Write(result);
HttpContext.Current.Response.End();


前台:

var clientUrl = "http://localhost:63526/UKWebService.asmx/GetUserInfoByUKNo?jsoncallback=?";
$.getJSON(
clientUrl,
{ UkNo: '201588884485' },
function (json) {
var r = eval(json);
alert(r[0].PersonName);
}
);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: