开发者

How to create in php a search.json twitter-like

I've made on my website a search.php file that produce a JSON string, he开发者_如何转开发lping me to use real-time ajax for my apps.

But now, I'd like to open it as an API to others, but I discovered that $.get $.getJSON $.ajax doesn't allow to use my search.php file from other servers/domains.

How can I do to transform my php search into a search.json, exactly like Twitter, passing parameters to it.

Thx


getJSON is limited by your browser's security restrictions that lock down non-origin domains. In order to do cross-domain, you have to use JSONP, which requires you wrap the data in a function that is defined by the callback variable (e.g. $_GET['jsonp_callback']). e.g.

Search.php

<?php
    echo $_GET['jsonp_callback'] . '(' . json_encode($data). ');'
    // prints: jsonp123({"search" : "value", etc. });
?>

jQuery

$.ajax({
  dataType: 'jsonp',
  data: 'search=value',
  jsonp: 'jsonp_callback',
  url: 'http://yourserver.com/search.php',
  success: function () {
    // do stuff
  },
});

Just make sure that the callback variable that you define in your php script matches the jsonp value that you call through the .ajax query (or it defaults to "callback").


Twitter uses two mechanisms to allow cross-domain access to the search.twitter.com domain: crossdomain.xml (for Flash) and JSONP (for JavaScript).

With JSONP, the calling JavaScript includes a callback=? parameter in the URL, where ? is the name of a callback function. The server-side script wraps the encoded JSON as:

?(<JSON here>)

This allows the query parameters to be encoded as the src URL of a script tag, allowing cross-domain access that XMLHttpRequest does not allow. When the data arrives, it is executed as a script. The JavaScript interpreter decodes the JSON since it is a valid subset of JavaScript and then calls the callback function with the decoded JSON as an argument. It shouldn't take more than a few lines of code to implement JSONP in your PHP script.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜