阿宽

Nothing is more powerful than habit!
随笔 - 692, 文章 - 4, 评论 - 388, 阅读 - 149万
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

跨域-使用JSONP

Posted on   宽田  阅读(648)  评论(0编辑  收藏  举报

文章目录:

    跨域-知识

    跨域-使用JSONP

    跨域-使用js文件

    跨域-使用window.name

    跨域-使用Proxy page或Cross Frame      


 

    此为单向跨域。实现方法是域A向域B请求数据,域B生成JSONP的数据给A。我们使用Jquery实现通信。

 

    实现步骤:

    1、域A前端调用页面

复制代码
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<!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 runat="server">
    <title>无标题页</title>
    <script src="./js/jquery.1.3.2.js" type="text/javascript"></script>
    <script type="text/javascript">
    
function getData()
    {
        
var url = "http://b.5173.com/Default.aspx";  
        $.ajax({  
                url:url,  
                dataType:
"jsonp",  
                success: 
function(json){  
                             alert(json.msg);
                          },  
                error: 
function(){
                         alert(
"error");
                         }  
               })  
    }
    
</script>
</head>
<body>
    <form id="form1" runat="server">
    <input type="button" value="跨域调用" onclick="getData();"/>
    </form>
</body>
</html>
复制代码

 

    2、域B主要是生成Jsonp,所以只有后台代码。

复制代码
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace WebApplication2
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Charset = "utf-8";
            Response.ContentType = "text/javascript";
            

            string callback = Request.QueryString["callback"];
            string json = "{'state':'0','msg':'hello world!'}";
            string result = string.Format("{0}({1})",callback,json);
            
            
            Response.Write(result);
            Response.Flush();
            Response.End();
            
            
        }
    }
}
复制代码

 

 

    调用结果: 

 

 

 

参考文章:http://www.cnblogs.com/hb_cattle/archive/2011/10/27/1713659.html

 

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
历史上的今天:
2008-11-12 Oracle中的to_date()函数
2008-11-12 Ms-Sql数据库文件太大处理
2008-11-12 如何查看Ms-sql调度
2007-11-12 C# 操作符重載學習
点击右上角即可分享
微信分享提示