How to access different domain data using Java script

自闭症网瘾萝莉.ら 提交于 2019-12-12 06:18:25

问题


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


回答1:


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);
});


来源:https://stackoverflow.com/questions/2616985/how-to-access-different-domain-data-using-java-script

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