如何在php中创建一个search.json类似Twitter的内容 [英] How to create in php a search.json twitter-like
问题描述
我在我的网站上制作了一个search.php文件,该文件生成一个JSON字符串,可以帮助我在自己的应用程序中使用实时ajax.
但是现在,我想将其作为对其他人的API来打开,但是我发现$ .get $ .getJSON $ .ajax不允许使用其他服务器/域中的search.php文件. /p>
如何将我的php搜索转换为search.json,就像Twitter一样,将参数传递给它.
Thx
getJSON受浏览器的安全限制所限制,该安全限制可锁定非起源域.为了进行跨域,您必须使用JSONP,这需要将数据包装在由回调变量(例如$ _GET ['jsonp_callback'])定义的函数中.例如
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
},
});
只需确保您在php脚本中定义的回调变量与通过.ajax查询调用的jsonp值匹配(或者默认为回调").
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
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").
这篇关于如何在php中创建一个search.json类似Twitter的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!