Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于js跨域实践 #49

Open
Hibop opened this issue Oct 17, 2018 · 0 comments
Open

关于js跨域实践 #49

Hibop opened this issue Oct 17, 2018 · 0 comments

Comments

@Hibop
Copy link
Owner

Hibop commented Oct 17, 2018

CORS()

jsonp

要点:

  • 带src的标签具有跨域请求资源的能力
  • 客户端定义函数并将函数名传给服务端、服务端调用函数将数据作为实参传回
// client
<script>
var jsonCallback  = (data) => {
   console.log(data)
   // 拿到跨域数据
}
</script>
<script src="http://api.server.com/data/?format=jsonp&callback=jsonCallback"></script>

// server  data.js
callback({...data})

一个栗子,调用世界银行开放api
https://api.worldbank.org/region/?format=jsonp&prefix=getData

jquery在处理jsonp类型的ajax时:

jQuery(document).ready(function(){ 
        $.ajax({
             type: "get",
             async: false,
             url: "https://api.worldbank.org/region/",
             dataType: "jsonp",
             jsonp: "prefix",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)
             jsonpCallback:"flightHandler",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据
             success: function(json){
                 alert('您查询到航班信息:票价: ' + json.price + ' 元,余票: ' + json.tickets + ' 张。');
             },
             error: function(){
                 alert('fail');
             }
         });
     });

jQuery在处理时,自动帮你生成回调函数并把数据取出来供success属性方法来调用。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant