冰豆网

分享网络精彩
bingdou.com.cn

jQuery Ajax 实现跨域请求JSONP

时间:2020-11-17加入收藏

相信好多朋友在使用jQuery进行Ajax请求接口的时候会出现 No 'Access-Control-Allow-Origin' header is present on the requested resource 然后请求失败,下面我们来简单的解决这个问题。
直接上代码

<script type="text/javascript" src="/jquery-1.4.2.min.js"></script>  
<script type="text/javascript">  
$(function(){  
$.ajax(  
    {  
        type:'get',
        url : 'http://你的域名/test.php',
        dataType : 'jsonp',  //这里是重点,dataType 一定为 'jsonp'
        jsonp:"jsoncallback",//这里也是重点,jsonp 后面是返回格式!
        success  : function(data) {
            console.log(data);
        },  
        error : function(error) {
            console.error(error);
        }  
    }  
);  
})  
</script>

如果请求的是自己的接口,比如PHP为例
只需要在PHP接口文件里加入一段代码即可

header("Access-Control-Allow-Origin:*");

请求别人的接口无跨域,则用JSONP请求,自己的接口直接加上 header("Access-Control-Allow-Origin:*"); 然后用$.ajax或者$.get或者$.post直接请求即可。

打 赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

TGA: php 技巧

分享到:


官方微信二维码冰豆网官方微信公众号