jquery jsonp 跨域请求


jquery 的ajax增加了 datatype = jsonp  可以跨域请求 于是尝试请求局域网另外一台服务器 192.168.1.112 


php 后台通过 echo json_encode(array('code'=>'0','data'=>'hello world'));


请求写法:

<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>  
<script type="text/javascript">  
$(function(){    
$.ajax(  
    {  
        type:'post',  
        url : 'http://192.168.1.112/index.php/Webapi/Index/termTree/',   
        dataType : 'jsonp',  
        jsonp:"jsoncallback",  
        success  : function(data) {   
            console.log(data);   
        },  
        error : function() {  
            alert('fail');  
        }  
    }  
); 
})  
</script>  


<p>但是请求报错: </p><p></p><pre name="code" class="plain">Uncaught SyntaxError: Unexpected token :?jsoncallback=jQuery21404450890338048339_1469165393487&_=1469165393488:1 



原来错误的原因是 jsonp 和 json是两码事儿  

jsonp 请求json就会报错 因此需要修改后台输入 jsonp



调整后的后台代码 php:

<pre name="code" class="php">                $data = array('code'=>'0','data'=>'hello world');
<span style="white-space:pre">		</span>$callback = I('<span style="color:#ff0000;"><strong>jsoncallback</strong></span>');
                exit( <strong><span style="color:#ff0000;">$callback.'('.encode_json($data).')' </span></strong>);






调整后的前台请求:


<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>  
<script type="text/javascript">  
$(function(){    
$.ajax(  
    {  
        type:'post',  
        url : 'http://192.168.1.112/index.php/Webapi/Index/termTree/',  
<span style="white-space:pre">	</span><strong><span style="color:#ff0000;">data : 'returnType=jsonp',</span></strong>
        dataType : 'jsonp',  
        jsonp:"<strong><span style="color:#ff0000;">jsoncallback</span></strong>",  
        success  : function(data) {   
            console.log(data);   
        },  
        error : function() {  
            alert('fail');  
        }  
    }  
); 
})  
</script>  


但是请求报错: 

Uncaught SyntaxError: Unexpected token :?jsoncallback=jQuery21404450890338048339_1469165393487&_=1469165393488:1 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章