好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

php利用json数据实现跨域操作实例 - php高级应用

php利用json数据实现跨域操作实例

某网站后台用php脚本得到一个JSON格式的数据,交给前台javascript进行处理,使用JSON实现数据的跨域调用.

后台profile.php代码如下:

<?php    $arr  =  array (         'firstname'  => iconv( 'gb2312' ,  'utf-8' ,  '非诚' ),         'lastname'  => iconv( 'gb2312' ,  'utf-8' ,  '勿扰' ),         'contact'  =>  array (             'email'  => 'fcwr@HdhCmsTestphpfensi测试数据' ,             'website'  => 'http://HdhCmsTestphpfensi测试数据' ,        )    );    //将一个数组JSON   $json_string  = json_encode( $arr );   //此处注意,双引号能对里面的变量当变量进行处理,单引号则不会    echo   "getProfile($json_string)" ;  ?>  

需要指出的是,在非UTF-8编码下,中文字符将不可被encode,结果会出来空值,所以,如果你使用 gb2312编写PHP代码,那么就需要将包含中文的内容使用iconv或者mb转为UTF-8再进行json_encode.

前台index.html代码如下:

< script   type = "text/javascript" >    function getProfile(str) {        var  arr  =  str ;        document.getElementById("firstname") .innerHTML  =  arr .firstname;    }    </ script >    < body >   < div   id = "firstname" > </ div >   </ body >    <!-- 使用JSON实现跨域的数据调用,此处如将[profile.php]改为[http://另外一个域名/profile.php]就更能看出跨域了-->   < script   type = "text/javascript"   src = "profile.php" > </ script >  

将JSON格式的数据直接赋值给javascript中的变量,就变成数组了,接下来操作起来就会非常的方便,此处如果使用XML做为数据传输,后续操作就不方便.

很显然,当index.html调用profile.php时,JSON字符串生成,并作为参数传入getProfile,然后将昵称插入到div 中,这样一次跨域数据交互就完成了调用index.html.

查看更多关于php利用json数据实现跨域操作实例 - php高级应用的详细内容...

  阅读:47次