jQuery实现跨域访问的JSONP示例

作者:阿沐

时间:2026-10-28

浏览:479

本文通过jQuery AJAX与C# WebHandler示例,演示如何使用JSONP解决跨域访问问题。客户端配置jsonp参数,服务端返回带回调函数的JSON数据,实现不同域名间的数据交互。

文章目录

客户端jQuery AJAX跨域请求配置

代码实现如下:

 
<div id="oid"></div>
<script type="text/javascript">
// 获取货号逻辑
$.ajax({
url: "http://192.168.1.191/H.ashx",
type: "GET",
dataType: 'jsonp',
// jsonp参数名可自定义,若使用jsoncallback,服务端需返回对应回调对象。
jsonp: 'jsoncallback',
// 必须声明参数,无参时亦需保留此配置
data: null,
timeout: 5000,
// 指定返回Json类型
contentType: "application/json;utf-8",
// 服务端返回对象需包含name与openid字段。
success: function (result) {
document.getElementById('oid').innerText=result.name+":"+result.openid;
}, 
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
} 
}); 
</script>

服务端C# WebHandler处理逻辑

服务端 H.ashx


代码实现如下:

 
<%@ WebHandler Language="C#" Class="H" %>
using System;
using System.Web;
public class H : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
string result = context.Request.QueryString["jsoncallback"] + "({\"name\":\"测试编号为\",\"openid\":\"123456789\"})";
context.Response.Clear();
context.Response.Write(result);
context.Response.End();
} 
public bool IsReusable {
get {
return false;
} 
} 
} 

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章