加入收藏 | 设为首页 | 会员中心 | 我要投稿 核心网 (https://www.hxwgxz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 业界 > 正文

使用Jquery中getJSON和getScript方法实现跨域

发布时间:2018-08-26 07:50:17 所属栏目:业界 来源:站长网
导读:一、什么是跨域? 因为javascript同源策略的限制,a.com 域名下的js脚本无法操作b.com或是c.a.com域名下的对象。 1.什么引起了ajax不能跨域请求的问题? ajax本身实际上是通过XMLHttpRequest对象来进行数据的交互,而浏览器出于安全考虑,不允许js代码进行

如果是自己项目的话,自己在后台构建这样一个字符串返回就OK了。

2.用getjson的回调,获取JSON数据 

Copy to ClipboardLiehuo.Net Codes引用的内容:[www.veryhuo.com] <script type="text/javascript">
$.getJSON("http://localhost:3856/GetItemCates.ashx/GetItemCats?gateid=20&format=json&jsoncallback=?",
function (data) {
var myprops = data.itemcats_get_response.item_cats.item_cat;
$.each(myprops, function (index, item) { $("ul").append("<li>" + item.name + "," + item.cid + "</li>") });
}

);
</script>

这是我在本地建立的一个测试项目,不同的端口,协议,都算不同的域。不多说贴代码,代码其实是调用淘宝的一个API取得淘宝的商品分类信息,CID这个参数是父类的ID,顶级为0.

实际上请求的地址是:http://localhost:3856/GetItemCates.ashx/GetItemCats?gateid=20&format=json&jsoncallback=jsonp1322444422697,

发送到数据接收方的地址后面一定要加上jsoncallback=?这样的参数,且这个?是会被Jquery自动替换成回调方法的名称。

Copy to ClipboardLiehuo.Net Codes引用的内容:[www.veryhuo.com] public class GetItemCates : IHttpHandler
{
private readonly static string url = "http://gw.api.taobao.com/router/rest";
private readonly static string appkey = "12409166";
private readonly static string appsecret = "*******";
ITopClient client = new DefaultTopClient(url, appkey, appsecret, "json");
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
context.Response.ContentEncoding =System.Text.Encoding.UTF8;

string cid = context.Request["gateid"];
string callback = context.Request["jsoncallback"];

if (!string.IsNullOrEmpty(cid))
{
context.Response.Write(callback+GetItemCats(Convert.ToInt64(cid)));
}
}

public string GetItemCats(Int64 cid)
{

ItemcatsGetRequest req = new ItemcatsGetRequest();
req.Fields = "cid,parent_cid,name,is_parent,status,sort_order";
req.ParentCid = cid;
ItemcatsGetResponse response = client.Execute(req);
return "("+response.Body+")";
}

public bool IsReusable
{
get
{
return false;
}
}
}

(编辑:核心网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读