利用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模糊演示样例-RenderScript-附效果图与代码
本文链接 http://blog.csdn.net/xiaodongrush/article/details/31031411 參考链接 Android高级模糊技术 http://s ...
- 【转】Spring的中IoC及AOP
1. Spring介绍 Spring是轻量级的J2EE应用程序框架.Spring的核心是个轻量级容器(container),实现了IoC(Inversion of Control)模式的容器,Spri ...
- 算法笔记_104:蓝桥杯练习 算法提高 新建Microsoft Word文档(Java)
目录 1 问题描述 2 解决方案 1 问题描述 问题描述 L正在出题,新建了一个word文档,想不好取什么名字,身旁一人惊问:“你出的题目叫<新建Microsoft Word文档>吗? ...
- java阅读笔记
前言:面向对象设计的几大原则? 1>针对接口编程,而不是针对实现编程 2>优先使用对象组合,而不是类继承 1.只根据抽象类中定义的接口来操纵对象有以下两个好处? 1)客户无须知道他们使用对 ...
- js声明变量的三种方式及作用域
js声明变量的三种方式及作用域 CreateTime--2017年9月11日17:19:11 Author:Marydon 一.参考链接 本篇文章的创作灵感来源于博主-奔跑的铃铛关于js中cons ...
- js 时间戳
https://www.cnblogs.com/crf-Aaron/archive/2017/11/16/7844462.html var time = '2018-03-22 00:00:00'.r ...
- wpf 帧动画
帧动画实现很简单 <ImageBrush x:Key="speed_s" Stretch="Fill" ImageSource="/images ...
- 3.Queues(队列)
一.概述 C++队列是一种容器适配器,它给予程序员一种先进先出(FIFO)的数据结构,与stack刚好相反. 二.常用API back() 返回最后一个元素 empty() 如果队列空则返回真 fro ...
- 新标准C++程序设计读书笔记_继承和多态
简单继承的例子: #include <iostream> #include <string> using namespace std; class CStudent { pri ...
- CSU 1335: 高桥和低桥 (二分查找,树状数组)
Description 有个脑筋急转弯是这样的:有距离很近的一高一低两座桥,两次洪水之后高桥被淹了两次,低桥却只被淹了一次,为什么?答案是:因为低桥太低了,第一次洪水退去之后水位依然在低桥之上,所以不 ...