jquery跨域ajax怎样使用?主机上的hello.php代码如下:<?php
$arr=array(
"hello"=>"world"
);
$json=json_encode($arr);
echo $json;
?>网址:http://www.your-dede.info/my_question/jsonp/hello.php本地localhost的index.htm代码如下:<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
function hello(){
$.ajax({
type:"GET",
dataType:"jsonp",
url:"http://www.your-dede.info/my_question/jsonp/hello.php",
success: function(html){
alert(html);
}
});
}
</script>
<button onclick="hello();">hello</button>打开本地index.htm网址,firefox报错:invalid label
请问怎样才能获取跨域内容?

解决方案 »

  1.   

    js 跨域用 iframe 或者 script 标签
      

  2.   

    使用以下的代码试一试,跨域请求注册的回调函数好像是在jsonp的属性。<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script type="text/javascript">
        function sayhello(html){
            alert(html);   
        }
        function hello(){
            $.ajax({
                type:"GET",
                dataType:"jsonp",
                url:"http://www.your-dede.info/my_question/jsonp/hello.php",
                jsonp: "sayhello"
            });
        }
    </script>
    <button onclick="hello();">hello</button>
      

  3.   

     // 动态导入js
    function include(src,encoding,fun) 

        var s = document.createElement('script');   
        s.type='text/javascript';
        s.charset=encoding; //'gb2312';
        s.src = src;   
        var tags =document.getElementsByTagName('head');   
       if(typeof(fun)=='function'){
            if( document.all ){
               s.onreadystatechange = function(){
                    if(/(complete|loaded)/.test(this.readyState)){
                          fun(); s.onreadystatechange = null; s.parentNode.removeChild(s); 
                     }};
           }else{
                 s.onload = function(){  fun(); s.onload = null; s.parentNode.removeChild(s); };
           }
        } 
        tags[0].appendChild(s); 
    };
    hello.php 页面(输出)返回:__rs={msg:'hello',value:true};
    include("http://www.your-dede.info/my_question/jsonp/hello.php","utf-8",function(){
    // 回调函数
    服务器只能输出一个全局变量,供客户端处理
    if(__rs && __rs.value){alert(__rs.msg);}
    });