利用JQuery jsonp实现Ajax跨域请求 .Net 的*.handler 和 WebService,返回json数据
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数据的更多相关文章
- 利用jsonp进行Ajax跨域请求
在进行Ajax请求的时候经常会遇到跨域的问题,这个时候一般就会用到jsonp. 关于json和jsonp,网上有很多原理解释,这里就不多赘述,需要的自行搜索. 下面是一个简单的ajax跨域请求示例: ...
- JSONP实现Ajax跨域请求
前言 由于浏览器存在同源策略的机制,所谓同源策略就是阻止从一个源(域名,包括同一个根域名下的不同二级域名)加载的文档或者脚本获取/或者设置另一个源加载的文档属性. 但比较特别的是:由于同源策略是浏览器 ...
- 关于试用jquery的jsonp实现ajax跨域请求数据的问题
我们在开发过程中遇到要获取另一个系统数据时,就造成跨域问题,这就是下文要说的解决办法: 先我们熟悉下json和jsonp的区别: 使用AJAX就会不可避免的面临两个问题,第一个是AJAX以何种格式来交 ...
- 关于JQuery 中$.ajax函数利用jsonp实现Ajax跨域请求ASP.NET的WebService成功获取数据的案例
部署环境:Window 7 SP1+IIS7 成功方案: 其成功解决问题的几个重要因素如下: 1. 由于WebService默认不支持Get请求,所以要在Web.config配置文件内的& ...
- 使用jsonp实现ajax跨域请求
Jsonp(JSON with Padding)是资料格式 json 的一种“使用模式”,可以让网页从别的网域获取资料. 由于同源策略,一般来说位于 server1.example.com 的网页无法 ...
- SpringMVC中利用@CrossOrigin注解解决ajax跨域请求的问题
1. 什么是跨域 跨域,即跨站HTTP请求(Cross-site HTTP request),指发起请求的资源所在域不同于请求指向资源所在域的HTTP请求. 2. 跨域的应用情景 当使用前后端分离,后 ...
- AJAX 跨域请求 - JSONP获取JSON数据
Asynchronous JavaScript and XML (Ajax ) 是驱动新一代 Web 站点(流行术语为 Web 2.0 站点)的关键技术.Ajax 允许在不干扰 Web 应用程序的显示 ...
- jquery ajax跨域请求详解
本文章来给大家详细jquery中的ajax跨域请求, 在JQuery对于Ajax的跨域请求有两类解决方案,不过都是只支持get方式.分别是JQuery的jquery.ajax jsonp格式和jque ...
- AJAX 跨域请求的解决办法:使用 JSONP获取JSON数据
由于受到浏览器的限制,ajax不允许跨域通信.如果尝试从不同的域请求数据,会出现安全错误.如果能控制数据驻留的远程服务器并且每个请求都前往同一域,就可以避免这些安全错误.但是,如果仅停留在自己的服务器 ...
随机推荐
- android adb 权限改动
1. 改动 ADB ROOT权限: system/core$ git diff adb/adb.c diff --git a/adb/adb.c b/adb/adb.c index 99bea0f.. ...
- python安装libxml2和pyquery
安装.net framework 4.5.2 https://www.microsoft.com/zh-CN/download/details.aspx?id=42641 安装C编译器 python2 ...
- 关于ThreadLocal变量的一个坑
每个线程都有一个ThreadLocalMap对象,ThreadLocalMap是Thread的一个内部类,可以把ThreadLocalMap理解成一个Map,这个Map里存放这一个Thread的所有线 ...
- Java教程到处都是,究竟怎样能学好Java?
学习Java如何入门?学习教程要点是什么?如何精通?做好以下这些点,入门更快,掌握Java更轻松. Java必备基础知识 1.你需要精通面向对象分析与设计(OOA/OOD).涉及模式(GOF,J2EE ...
- angularJS 状态样式绑定
angularJS提供输入框不同状态下的样式绑定 输入框有4种状态 ng-model 指令可以为应用数据提供状态值(invalid, dirty, touched, error): <!DOCT ...
- C# EF使用性能消耗列表 https://msdn.microsoft.com/zh-cn/library/cc853327.aspx
性能注意事项(实体框架) .NET Framework (current version) 其他版本 本主题介绍 ADO.NET 实体框架的性能特征,并提供一些注意事项帮助改善实体框架应用程序 ...
- java 解析webservice 中的soapheader
//从MessageContet中获取头域中的值 public HeaderBean getBeanFromRequest(org.apache.axis2.context.MessageContex ...
- 【VBA研究】利用DateAdd函数取上月或上年同期的日期
作者:iamlaosong DateAdd函数返回一个日期.这一日期加上了一个时间间隔.通过这个函数能够计算非常多我们须要的日期,比方上月上年同期日期等. 语法 DateAdd(interval, n ...
- 求1,1,2,3,5,8,13 斐波那契数列第N个数的值
朋友问了个斐波那契算法.我给出了个递归算法 public static int Foo(int n) { ) { return n; } else { ) + Foo(n - ); } } 结果被打击 ...
- 删除MYSQL账号多于的空用户
默认情况下,mysql安装好之后,会存在匿名用户,也可以叫空用户,输入mysql之后直接回车便可进入mysql. 该匿名用户具有一定的权限,通过SHOW DATABASES;可以查看到informat ...