php利用json数据实现跨域操作实例
本文章简单的介绍了关于如何利用php利用json数据实现跨域操作实例,有需要的同学可以参考一下下哈。
:某网站后台用php脚本得到一个JSON格式的数据,交给前台javascript进行处理,使用JSON实现数据的跨域调用
后台profile.php代码:
代码如下 | 复制代码 |
$arr = array( 'firstname' => iconv('gb2312', 'utf-8', '非诚'), 'lastname' => iconv('gb2312', 'utf-8', '勿扰'), 'contact' => array( 'email' =>'fcwr@hzhuti.com', 'website' =>'http://www.hzhuti.com', ) ); //将一个数组JSON $json_string = json_encode($arr); //此处注意,双引号能对里面的变量当变量进行处理,单引号则不会 echo "getProfile($json_string)"; ?> |
需要指出的是,在非UTF-8编码下,中文字符将不可被encode,结果会出来空值,所以,如果你使用 gb2312编写PHP代码,那么就需要将包含中文的内容使用iconv或者mb转为UTF-8再进行json_encode。
前台index.html代码:
代码如下 | 复制代码 |
|
将JSON格式的数据直接赋值给javascript中的变量,就变成数组了,接下来操作起来就会非常的方便,此处如果使用XML做为数据传输,后续操作就不方便喽。
很显然,当index.html调用profile.php时,JSON字符串生成,并作为参数传入getProfile,然后将昵称插入到div 中,这样一次跨域数据交互就完成了
调用index.html

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver Mac version
Visual web development tools