开发者

Get json result from non local server

开发者 https://www.devze.com 2023-03-30 00:45 出处:网络
I use following code for get json encoded result $.get(\'localhost/hospital/index/json\', function(data) {

I use following code for get json encoded result

$.get('localhost/hospital/index/json', function(data) {
   alert(data);
});

It is work for localhost URL. But I want get result from external server. I try following example url to do it.

$.get('hospitalsystem.dev/index/json', function(data) {
   alert(data);
});

But it is not working. Ple开发者_Go百科ase help me.


Omitting the http:// from the URL, as in your code snippet, can prevent the request from working, as shown in this example.

AJAX requests are limited by Same Origin policy, meaning that you can only make requests to the same domain. There are three main ways to get around this:

  • JSONP involves adding an argument to an API to function as a javascript file. JQuery can make this as simple as a normal AJAX request. A big problem with this is that it requires you to trust the provider of the API you're calling not to do anything malicious, such as transmitting cookies back to them.

  • Cross-Origin Resource Sharing is a more elegant solution, but only works in some browsers.

  • Creating a proxy for AJAX requests works with virtually any API, but adds some additional overhead and having two requests instead of one for each AJAX request may impact performance.


For security reasons, you cannot use AJAX to read data from a different domain.

You should modify the server to use JSONP.


Then use JSONP. Because AJAX calls doesn't work when url is on another server.

So what you need to do is read about JSONPand find a way to use it.

That is basically JSON but in the form of js file, like

<script language="javascript" src="/js/my.js"></script>

just instead /js/my.js use your location, there is no other way, believe me.

Use jQuery to dynamically load scripts from different urls and use data returned by them.


Based on your Server capability you can write an proxy script. Your JS ask the proxy to fetch and response the json file.

For Example: craigslist rss feed

0

精彩评论

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

关注公众号