前端之家收集整理的这篇文章主要介绍了
Jsonp实现跨域请求数据,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<Meta charset="utf-8">
<title>旅游见闻</title>
<Meta name="description" content="">
<Meta name="keywords" content="" />
<Meta name="viewport" content="initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width" />
<Meta name="format-detection" content="telephone=no" />
<Meta name="apple-mobile-web-app-capable" content="yes" />
<Meta name="apple-touch-fullscreen" content="yes" />
<Meta name="apple-mobile-web-app-status-bar-style" content="black" />
<link rel="apple-touch-icon-precomposed" href="http://10.1.13.8:814/apple-touch-icon-144x144-precomposed.png" />
<link rel="apple-touch-startup-image" href="http://10.1.13.8:814/apple-touch-icon-144x144-precomposed.png" />
<link rel="stylesheet" href="http://10.1.13.8:814/content/m/css/core.css">
<script src="http://r01.uzaicdn.com/Scripts/m/sea-modules/seajs/seajs/2.1.1/sea.js"></script>
<script src="http://r01.uzaicdn.com/Scripts/m/config.min.js"></script>
<script type="text/javascript">
var isRequestEnabled = true;
seajs.use(['http://r01.uzaicdn.com/scripts/m/core.min'],function (core) {
$(function () {
$('#zixun-list').find('.fn-more').on('click',getData);
});
$().ready(function () {
getCategoryName();
getData();
});
});
function getCategoryName() {
var CategoreID = $("#CategoreID").html();
$.ajax({
url: 'ArticleHandler.ashx?queryType=1&CategoreID=' + CategoreID + '&callback=?',dataType:"jsonp",success: function (data) {
$("#categoryName").html(data.CategoryName);
}
})
}
function getData() {
if (isRequestEnabled == false) {
return false;
}
var o = $(this);
var op = parseInt(o.attr('data-page'));
var CategoreID = $("#CategoreID").html();
var PageSize = $("#PageSize").html();
$.ajax({
url: 'ArticleHandler.ashx?pnum=' + op + '&CategoreID=' + CategoreID + '&PageSize=' + PageSize + '&callback=?',dataType: "jsonp",success: function (data) {
var msg =data;
if (msg.length > 0) {
for (var i = 0; i < msg.length; i++) {
var content = msg[i].ArticleContent;
if (content != undefined && content.length > 100) {
content = content.substring(0,100);
}
var data = "<li class='mb5' style='clear:both;'>";
data += "<a href='" + msg[i].ArticleUrl + "' class='block clearfix'><p class='tit f14 f333'>" + msg[i].ArticleTitle + "</p><div class='pic mr10'><img src='" + msg[i].ArticleListImg + "' width='50' height='45' /></div><div class='left-txt'>" + content + "</div></a>";
data += "</li>";
$('#zixun-list').find('ul').append(data);
}
o.attr('data-page',op + 1);
} else {
o.text('没有更多了..');
isRequestEnabled = false;
}
}
})
return false;
}
</script>
<style>
.zixun-list li { border-bottom:1px solid #eee;}
.zixun-list li:last-child { border-bottom:none;margin-bottom:0;}
.zixun-list li a { display:block;}
.zixun-list li .pic {width:50px;float:left;margin-top:4px; }
.zixun-list li .txt {margin-left:60px;word-wrap:break-word;}
.zixun-list li .tit { overflow:hidden;text-overflow:ellipsis;height:22px;white-space:nowrap;}
.left-txt{float:left;color:#999;font-size:12px;width:560px;}
</style>
</head>
<body>
<div class="wrap w reg">
<header class="fn-header">
<div class="fl icon back" onclick="javascript:history.go(-1);"></div>
<span class="tit" id="categoryName"></span>
</header>
<article>
<div class="zixun-list p10" id="zixun-list">
<ul>
</ul>
<p data-action="sort" data-page="2" class="fn-more" id="getmore"><a href="#">点击查看更多...</a></p>
</div>
</article>
<footer class="fn-footer">
<p class="p1"><a href="http://u.uzai.com/mobile/login">登录</a><a href="http://u.uzai.com/mobile/reg">注册</a><a href="http://u.uzai.com/mobile/order">我的订单</a><a href="http://m.uzai.com/about.html">关于悠哉</a><a href="http://m.uzai.com/">首页</a></p>
<p class="p2 orange"><a href="http://www.uzai.com">电脑版</a><a href="http://wap.uzai.com/app">客户端</a> <span><a href="#">TOP</a></span></p>
<p class="p3">©2013 悠哉旅游网 预订热线:400-000-8888</p>
</footer>
<div style="display:none" id="CategoreID">{$CategoreID}</div>
<div style="display:none" id="PageSize">5</div>
</div>
<script type="text/javascript">
var _gaq = _gaq || []; //定义GA变量数组。
_gaq.push(['_setAccount','UA-24479793-2']); //设置本跟踪代码所对应的Google帐户。
_gaq.push(['_trackPageview']); //定义按页面跟踪
(function () {//定义匿名的执行方法
var ga = document.createElement('script'); //定义GA的脚本Dom对象。到时候会appendChild到Document中
ga.type = 'text/javascript'; //不解释
ga.async = true; //定义GA数据传输方式为异步传输。
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; //定义GA的JS源路径,自动取的,主要是做了一个协议判断,意味着GA可以跟踪htts网页和ssl网页,当你 的页面是http时就去http://www.google-analytics.com/ga.js取代码。当你是https页面时就去https://www.google-analytics.com/ga.js取代码。
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga,s); //添加GA代码
})();
</script>
</body>
</html>
二、jsonp请求的服务类
注:(此类可以为其他域名下)
<%@ WebHandler Language="C#" Class="ArticleHandler" %>
using System;
using System.Web;
public class ArticleHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
string responseJson = string.Empty;
int pageIndex=5;
int categoryId=0;
int pageSize=0;
//获取回调函数名
string callback = context.Request.QueryString["callback"];
//请求的页码
string pageIndexStr = context.Request.QueryString["pnum"];
if (string.IsNullOrEmpty(pageIndexStr) || !Int32.TryParse(pageIndexStr,out pageIndex))
{
//传递的pageIndex无效,则设置为1
pageIndex = 1;
}
//文章列表分类ID
string categoryStr = context.Request.QueryString["CategoreID"];
//文章列表分类页面个数
string pageSizeStr = context.Request.QueryString["PageSize"];
if (!string.IsNullOrEmpty(pageSizeStr) && Int32.TryParse(pageSizeStr,out pageSize))
{
//如果页面个数为空,则设置为
pageSize = Convert.ToInt32(pageSizeStr);
}
if (!string.IsNullOrEmpty(categoryStr) && Int32.TryParse(categoryStr,out categoryId))
{
Uzai.Shop.BLL.BLLUzaiPhone.BLLUzaiPhoneAnnounce bllPhone = new Uzai.Shop.BLL.BLLUzaiPhone.BLLUzaiPhoneAnnounce();
string queryType = context.Request.QueryString["queryType"];
if (!string.IsNullOrEmpty(queryType))
{
//如果queryType参数存在则是请求分类名称
responseJson = bllPhone.GetCategoryById(categoryId).CategoryName;
responseJson = "{\"CategoryName\":\"" + responseJson + "\"}";
}
else
{
//请求文章数据-Json
responseJson = GetPages(categoryId,pageIndex,pageSize);
}
}
context.Response.ContentType = "application/json";
context.Response.Write(callback + "(" + responseJson + ")");
}
public bool IsReusable {
get {
return false;
}
}
}
/// <summary>
/// 按照文章分类编号来获取文章列表-分页
/// </summary>
/// <param name="categoryId">文章分类编号</param>
/// <param name="startIndex">起始下标</param>
/// <param name="pageIndex">每页个数</param>
/// <param name="allCount">总条数</param>
/// <returns>该文章分类下的文章列表</returns>
public IList<PhoneArticleListPage> GetArticleListByCategoryId(int categoryId,int pageIndex,int pageSize,out int allCount)
{
IList<PhoneArticleListPage> list = new List<PhoneArticleListPage>();
#region 得到总条数
allCount = 0;
string allCountsql = "select Count(1) FROM [UzaiPhoneArticleListPage] where SourceCategoryID = {0} ; ";
allCountsql = string.Format(allCountsql,categoryId);
object obj = sqlHelper.ExecuteScalar(sqlHelper.connstr,System.Data.CommandType.Text,allCountsql);
int count;
if (obj != null && Int32.TryParse(obj.ToString(),out count))
{
allCount = count;
}
#endregion
#region 得到文章
string sql = "select [ID],[ArticleTitle],[ArticleListImg],[ArticleContent],[ArticleUrl],[SourceCategoryID],[CreateTime],[Sort] from "
+ "(SELECT *,Row_Number() over(order by Sort asc) RowID "
+ "FROM [UzaiPhoneArticleListPage] where SourceCategoryID = {0}) temp "
+ "where temp.RowID > {1} and temp.RowID < {2} ";
int startIndex = (pageIndex - 1) * pageSize;
int endIndex = pageIndex * pageSize + 1;
sql = string.Format(sql,categoryId,startIndex,endIndex);
sqlDataReader reader = sqlHelper.ExecuteReader(sqlHelper.connstr,sql);
try
{
if (reader != null)
{
PhoneArticleListPage page;
while (reader.Read())
{
page = new PhoneArticleListPage();
page.ID = reader.GetInt32(0);
page.ArticleTitle = reader.GetString(1);
page.ArticleListImg = reader.GetString(2);
page.ArticleContent = reader.GetString(3);
page.ArticleUrl = reader.GetString(4);
page.SourceCategoryID = reader.GetInt32(5);
page.CreateTime = reader.GetDateTime(6);
list.Add(page);
}
reader.Close();
}
}
catch (Exception)
{
list.Clear();
}
#endregion
return list;
}
原文链接:https://www.f2er.com/json/290328.html