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

行使Jquery中getJSON和getScript要领实现跨域

发布时间:2018-08-25 00:35:45 所属栏目:业界 来源:站长网
导读:一、什么是跨域? 由于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;
}
}
}

(编辑:湖南网)

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

热点阅读