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);
}
);

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

  1. 利用jsonp进行Ajax跨域请求

    在进行Ajax请求的时候经常会遇到跨域的问题,这个时候一般就会用到jsonp. 关于json和jsonp,网上有很多原理解释,这里就不多赘述,需要的自行搜索. 下面是一个简单的ajax跨域请求示例: ...

  2. JSONP实现Ajax跨域请求

    前言 由于浏览器存在同源策略的机制,所谓同源策略就是阻止从一个源(域名,包括同一个根域名下的不同二级域名)加载的文档或者脚本获取/或者设置另一个源加载的文档属性. 但比较特别的是:由于同源策略是浏览器 ...

  3. 关于试用jquery的jsonp实现ajax跨域请求数据的问题

    我们在开发过程中遇到要获取另一个系统数据时,就造成跨域问题,这就是下文要说的解决办法: 先我们熟悉下json和jsonp的区别: 使用AJAX就会不可避免的面临两个问题,第一个是AJAX以何种格式来交 ...

  4. 关于JQuery 中$.ajax函数利用jsonp实现Ajax跨域请求ASP.NET的WebService成功获取数据的案例

    部署环境:Window 7 SP1+IIS7 成功方案: 其成功解决问题的几个重要因素如下: 1.       由于WebService默认不支持Get请求,所以要在Web.config配置文件内的& ...

  5. 使用jsonp实现ajax跨域请求

    Jsonp(JSON with Padding)是资料格式 json 的一种“使用模式”,可以让网页从别的网域获取资料. 由于同源策略,一般来说位于 server1.example.com 的网页无法 ...

  6. SpringMVC中利用@CrossOrigin注解解决ajax跨域请求的问题

    1. 什么是跨域 跨域,即跨站HTTP请求(Cross-site HTTP request),指发起请求的资源所在域不同于请求指向资源所在域的HTTP请求. 2. 跨域的应用情景 当使用前后端分离,后 ...

  7. AJAX 跨域请求 - JSONP获取JSON数据

    Asynchronous JavaScript and XML (Ajax ) 是驱动新一代 Web 站点(流行术语为 Web 2.0 站点)的关键技术.Ajax 允许在不干扰 Web 应用程序的显示 ...

  8. jquery ajax跨域请求详解

    本文章来给大家详细jquery中的ajax跨域请求, 在JQuery对于Ajax的跨域请求有两类解决方案,不过都是只支持get方式.分别是JQuery的jquery.ajax jsonp格式和jque ...

  9. AJAX 跨域请求的解决办法:使用 JSONP获取JSON数据

    由于受到浏览器的限制,ajax不允许跨域通信.如果尝试从不同的域请求数据,会出现安全错误.如果能控制数据驻留的远程服务器并且每个请求都前往同一域,就可以避免这些安全错误.但是,如果仅停留在自己的服务器 ...

随机推荐

  1. 饿了么ui添加事件

    最近饿了么ui挺火,连美团都有项目组再用,刚好最近项目重构,就引入了进来,刚用上就发现一个大坑,在配合vue使用时,居然无法添加自定义事件 找了半天才发现原因是需要在事件后面加上  ‘’.native ...

  2. LightOj 1221 - Travel Company(spfa判负环)

    1221 - Travel Company PDF (English) Statistics problem=1221" style="color:rgb(79,107,114)& ...

  3. 算法笔记_113:算法集训之代码填空题集一(Java)

     目录 1 报数游戏 2 不连续处断开 3 猜数字游戏 4 串的反转 5 串中找数字 6 递归连续数 7 复制网站内容 8 股票的风险 9 基因牛的繁殖 10 括号的匹配   1 报数游戏 有n个孩子 ...

  4. 算法笔记_062:蓝桥杯练习 最小乘积(基本型)(Java)

    目录 1 问题描述 2 解决方案   1 问题描述 问题描述 给两组数,各n个. 请调整每组数的排列顺序,使得两组数据相同下标元素对应相乘,然后相加的和最小.要求程序输出这个最小值. 例如两组数分别为 ...

  5. onethink 密码加密方式详解

    /** * 系统非常规MD5加密方法 * @param string $str 要加密的字符串 * @return string */ function think_ucenter_md5($str, ...

  6. Why do Antennas Radiate?

    Obtaining an intuitive idea for why antennas radiate is helpful in understanding the fundamentals of ...

  7. remove &#39;^M&#39; in shell script

    近期在windows上编辑一些shell脚本后上传到交换机框体上. 但这些shell脚本无法运行,每一行结尾都有'^M',同一时候框体上又没有dos2unix工具. 这么多脚本也不可能一行一行来改动. ...

  8. myBatis的引出

    jdbc 优点:简单易学,上手快,非常灵活构建sql,效率高. l缺点:代码繁琐,难以写出高质量的代码(资源的释放,SQL注入安全性等),开发者关注多,又要写业务逻辑,又要关注对象的创建和销毁. Hi ...

  9. [Java基础]List,Map集合总结

    java.util包下: Collection    |--List 接口 |----ArrayList |----LinkedList |----Vector |-----Stack |---Set ...

  10. windows Service 2012 系统时间格式带中文

    C# 获取DataTime.Now   显示     2019年4月23日 下午 10:03:00 导致转换格式失败, 因为 源码中写的是   DataTime.Now.ToString();   输 ...