博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JS跨域请求
阅读量:4489 次
发布时间:2019-06-08

本文共 1716 字,大约阅读时间需要 5 分钟。

一.跨域请求方式:

1.跨域请求方式一:angularjs之$http.jsonp

举例:

1 $http.jsonp( "http://xxx.xxx.com?action=getResource&userID=" + userId + "&resourceCode=" + code + "&callback=JSON_CALLBACK") 2 .success(function (data) { 3 var json = eval(data); 4 if (json.Success == 'True') { 5 window.location.href = json.Site; 6 }  7 else if (json.Success == 'False') { 8 alert(json.Site); 9 }10 11 })12 .error(function () {13 14 //process15 });

 

2.跨域请求方式二:jquery之$.ajax(或者$.getJSON)

同样举例:

1 var url = "http://xxx.xxx.com/xxx.svc/Jsonp/QueryTemplates?systemCode=_Ferry_";//此处请求WCF服务 2 //var mydata = { action: "getResource", userID: 428, resourceCode: 5507 }; 3  4  5 $.ajax({ 6 url: url, 7 type: 'GET', 8 dataType: 'jsonp',//必须 9 data: "{}",10 jsonp: 'callback',//必须11 success: function (result) {
//此处即为服务端返回的可执行js代码的默认执行函数(注:服务端一般返回 callback(jsondata) )12 13 for (var i in result) {14 alert(i + ":" + result[i]);//循环输出a:1,b:2,etc. 15 }16 },17 error: function (XMLHttpRequest, textStatus, errorThrown) {18 console.log(XMLHttpRequest);19 console.log(textStatus);20 console.log(errorThrown);21 },22 timeout: 300023 });

 

二.注意事项:

1.jsonp跨域只能GET,不能POST

2.服务端相应要做处理,如:
C# Code:

1 [WebMethod] 2 public void JQueryJsonp(string callback) 3  4 { 5  6 System.Web.HttpContext.Current.Response.Write(callback+"({username:'showbo'})"); 7  8 System.Web.HttpContext.Current.Response.End(); 9 10 }

 

Javascript Code:

1 $.ajax({2 url: "test.asmx/JQueryJsonp?callback=?",3 dataType: "jsonp",4 success: function (json) { alert("Success:" + json.username); },5 error: function (x, e) { alert("Error:" + x.responseText); }, 6 complete: function (x) { alert("Complete:" + x.responseText); }7 });

先记着,后续再补充完善。

转载于:https://www.cnblogs.com/zhanghua545588089/p/5908205.html

你可能感兴趣的文章
Validate Binary Search Tree
查看>>
签到新旧版本更替问题
查看>>
剖析WordPress模板文件【转】
查看>>
20145109 《Java程序设计》第七周学习总结
查看>>
面向面试编程-概念之-分布式与集群的区别和联系
查看>>
Object to xml 2
查看>>
SpringMVC——架构,搭建,SSM搭建,POST请求乱码问题,参数转换器
查看>>
测试驱动开发全功略(转)
查看>>
(2016弱校联盟十一专场10.2) E.Coins
查看>>
关闭蜂鸣最简单的方法
查看>>
第二章 springboot+mybatis
查看>>
Python与数据挖掘学习笔记(1)——Pandas模块
查看>>
mysql_affected_rows()、mysql_fetch_row、mysql_fetch_assoc
查看>>
C语言博客作业--结构体
查看>>
MATLAB 出一张好看的图
查看>>
EmptyRecycle() 清空回收站
查看>>
CentOS5.5环境下布署LVS+keepalived
查看>>
Google 周三宣布新版Google Trend上线
查看>>
二叉搜索树(搜索二叉树)转换成一个双向链表
查看>>
(转)Linux 系统性能分析工具图解读(一、二)
查看>>