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 

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