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

走远了吗. 提交于 2020-01-04 05:42:07

问题


I've made on my website a search.php file that produce a JSON string, helping 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


回答1:


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").




回答2:


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.



来源:https://stackoverflow.com/questions/3954558/how-to-create-in-php-a-search-json-twitter-like

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!