利用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不允许跨域通信.如果尝试从不同的域请求数据,会出现安全错误.如果能控制数据驻留的远程服务器并且每个请求都前往同一域,就可以避免这些安全错误.但是,如果仅停留在自己的服务器 ...
随机推荐
- 2013年八月GBin1月刊
2013年八月GBin1月刊 推荐十款来自极客标签的超棒前端特效[第十二期] 本周,我们带来了极客社区推荐的10款前端特效,仍然是非常有趣的小动态效果的页面生成.喜欢的可以直接将我们的在线调试代码插入 ...
- Springboot配置文件加载顺序
使用Springboot开发的时候遇到了配置的问题,外部config里的配置文件本来没有配置https怎么启动还是https呢,原来开发中测试https在classpath路径的配置文件添加https ...
- vue - .babelrc
描述:bable-es2015以及babel本身组件在新版本要求的外部配置文件. { "presets": [ ["env", { "modules& ...
- 算法笔记_091:蓝桥杯练习 递推求值(Java)
目录 1 问题描述 2 解决方案 1 问题描述 问题描述 已知递推公式: F(n, 1)=F(n-1, 2) + 2F(n-3, 1) + 5, F(n, 2)=F(n-1, 1) + 3F(n- ...
- 【Python 数据分析】module 'numpy' has no attribute 'array'
安装好Numpy模块后,开始做了几个小测试都可以运行,但是当我创建numpy.py这个文件后 numpy.py import numpy y = numpy.array([[11,4,2],[2,6, ...
- tomcat禁用webdav
在tomcat的web.xml,以及自己项目的web.xml中,均需添加以下内容: <security-constraint> <web-resource-collection> ...
- struts 简单前台用户名校验
一个jsp <?xml version="1.0" encoding="GB18030" ?> <%@ page language=" ...
- XML的SelectNodes使用方法以及XPath(转)
XPath 是 XML 的内容,这里 SelectNodes 是 C# 中 XmlDocument 或 XmlNode 的一个方法.SelectNodes 使用 XPath 来选取节点. 重要语法 S ...
- swipeRefreshLayout与webview滑动冲突
遇到这么个bug,webview使用swipeRefreshLayout时,下拉时事件不会被webview捕获,而是执行swipeRefreshLayout的刷新,网上一大堆一大堆的解决办法,都是什么 ...
- docker运行环境安装-centos(一)
在这里我们使用的是docker的社区版Docker CE,针对的是未安装docker的新的主机,如果安装过docker的早期版本,先卸载它们及关联的依赖资源,安装的版本为docker 18.03. 1 ...