现在的位置: 首页 > 综合 > 正文

PHP: How to easily provide JSON and JSONP

2013年10月02日 ⁄ 综合 ⁄ 共 1483字 ⁄ 字号 评论关闭

Would you like to grab some server-side data through an AJAX call? For example by using the handy jQuery.ajax method?

A good data format to use then is JavaScript
Object Notation
, more commonly known as JSON. Providing data in the JSON format with PHP is super duper simple 8)

JSON

All you need to do on the server side is to set the content-type to application/json,
encode your data using the json_encode function
and output it.

<?php header('content-type:
application/json; charset=utf-8'
);

$data = array(1, 2, 3, 4, 5, 6, 7, 8, 9);

echo json_encode($data);

You can test it out for example in the FireBug console
by running this line:

$.ajax({url: 'data.php'})
//
Response: [1,2,3,4,5,6,7,8,9]

You should see the request being done in the console and also in the Net tab. If it didn’t work, you might be subject to the following:

Due to browser security restrictions, most “Ajax” requests are subject to the same
origin policy
; the request can not successfully retrieve data from a different domain, subdomain, or protocol.

A nice and simple solution to that problem is JSON with padding, also known as JSONP.

JSONP

As stated on Wikipedia,

JSONP or “JSON with padding” is a complement to the base JSON data format, a usage pattern that allows a page to request and more meaningfully use JSON from a server other than the primary server.

I’m not sure I get everything about JSONP, but I have used it and I know that it works :PIt’s
almost just as easy as plain JSON actually, and all that’s needed is to wrap the JSON encoded data in a callback function provided as a GET parameter.

<?php header('content-type:
application/json; charset=utf-8'
);

$data = array(1, 2, 3, 4, 5, 6, 7, 8, 9);

echo $_GET['callback'] . '('.json_encode($data).
【上篇】
【下篇】

抱歉!评论已关闭.