Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

ajax - How to enable cross-domain request on the server?

I have a json file hosted on my server. When I try to make an Ajax "GET" request to the json file, it fails.

See the console in Safari, it says "Failed to load resource".

Firebug shows "200 OK", but the response doesn't show up. Even Firebug does not show the JSON tab.

I believe this is because Cross Domain Requests are not allowed using AJAX.

I would like to know how can I overcome this? Also, if I want to enable cross-domain requests on my server, I believe a crossdomain.xml file or something needs to be created. I am not sure, but this is what I know. I searched on Google, but could not find any relevant links.

Any help in this is highly appreciated.

Thanks.

UPDATE: I am not using any server-side scripting language (PHP, ASP.NET, etc). I am using Plain HTML and JavaScript / jQuery.

UPDATE-2:

I used the following code to make cross-domain requests:

<script src="jquery-1.6.2.js"></script>
  <script>
  $(document).ready(function () {
    $.ajax({
      dataType: 'jsonp',
      data: '',
      jsonp: 'jsonp_callback',
      url: 'http://myhosting.net/myjsonfile.json',
      success: function (jsonData) {
        alert("success")
        alert(jsonData);
      },
      error: function(errorObj) {
        alert(errorObj.statusText);

      },
    });
});

When i see in Firebug's "Net" tab, I see a JSON tab, and I am able to see the json response. However, the "success" callback handler doesn't get called, but the "error" callback handler gets invoked and I get the alert saying parseerror.

Any idea what could be wrong?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Access-Control-Allow-Origin: http://yourdomain-you-are-connecting-from.com

on target server

in php:

 header("Access-Control-Allow-Origin: http://yourdomain-you-are-connecting-from.com");

in case you don't want to use server-scripting language: put this in (linux) console

a2enmod headers

and to your .htaccess file add - - - - - - -

Header set Access-Control-Allow-Origin: http://yourdomain-you-are-connecting-from.com

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...