如何使用Java脚本访问不同的域数据 [英] How to access different domain data using Java script
问题描述
这里是问题。假设有 DOMAIN A 将成为包含 PHP Script 文件的服务器。来自域A的数据将由 DOMAIN B上的客户端访问。
我知道无法使用JavaScript直接访问。所以我做的是,在域A中,我创建了一个JavaScript文件作为前端的PHP脚本,AJAX的PHP和返回数据。但不幸的是它没有工作
我遇到了一个例子,PHP在客户端是一个中间人。但我不想保持任何服务器端PHP代码作为客户端的中间人。我只想将Javascript发送到客户端域。
DOMAIN A
PHP - data.php
<?php echo服务器返回数据; >
JS - example.js p>
Ajax到PHP
函数getData b {
//假设ajax对data.php完成,数据被检索,现在返回数据
return ajaxed_data;
}
域B
JS
客户端包括来自域A 的 example.js 文件HTML
< script type =text / javascriptsrc =http://www.DomainA.com/example。 js>< / script>
< script type =text / javascript>
alert(getData());
< / script>
我希望我已经明白了!这可以建立吗?它的东西像谷歌的朋友连接,我的意思是,只是提供JavaScript客户端和它。
DOMAIN A - data.php:
<?php
$ data ='{data :服务器返回数据}';
echo $ _GET ['jsoncallback']。 '('。$ data。');';
?>
DOMAIN B - 客户:
$ .getJSON('http://domainA.com/data.php?jsoncallback=?',function(json){
alert(json.data);
});
Here is the issue. Suppose there is a DOMAIN A which is going to be the server containing a PHP Script file. The data from Domain A is to be accessed by a Client at DOMAIN B.
I know it cannot be accessed directly using JavaScript. So what I did is, in Domain A I created a a JavaScript file as front-end for the PHP Script which AJAXes the PHP and returns the data. But unfortunately it din't work
I came across an example having PHP as a Middle Man in the client side. But I donot want to keep any server side PHP code as a middle man in the client side. I just want to give out the Javascript to the client domain.
How to get data with JavaScript from another server?
DOMAIN A
PHP - data.php
<?php echo "Server returns data"; ?>
JS - example.js
Does the Ajax to the PHP
function getData()
{
//assume ajax is done for data.php and data is retrieved, now return the data
return ajaxed_data;
}
Domain B
JS
Client includes the example.js file from Domain A in his HTML
<script type="text/javascript" src="http://www.DomainA.com/example.js"></script>
<script type="text/javascript">
alert(getData());
</script>
I hope I have made myself understandable ! Can this be established ? Its something like Google friend connect, what I mean is, just provide JavaScript to the client and thats it. Every thing carried out in server side
Thankx for providing this forum
You could use JSONP. jQuery has a good support for it.
DOMAIN A - data.php:
<?php
$data = '{ "data" : "Server returns data" }';
echo $_GET['jsoncallback'] . '(' . $data . ');';
?>
DOMAIN B - client:
$.getJSON('http://domainA.com/data.php?jsoncallback=?', function(json) {
alert(json.data);
});
这篇关于如何使用Java脚本访问不同的域数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!