XMLHttpRequest cannot load is not allowed by Access-Control-Allow-Origin

为君一笑 提交于 2019-12-17 16:18:33

问题


I'm trying to get access to education.com API data. However, I keep receiving an error the error states:

XMLHttpRequest cannot load http://api.education.com/service/service.php?f=schoolSearch&key=mykey&sn=sf&v=4&city=Atlanta&state=ga&Resf=json. Origin is not allowed by Access-Control-Allow-Origin.

My code is the following:

$(function(){
    $.getJSON('http://api.education.com/service/service.php?f=schoolSearch&key=mykey&sn=sf&v=4&city=Atlanta&state=ga&Resf=json', 
    function(data) {
        console.log(data);
    });
});

Can someone help me please?


回答1:


An article on Cross Domain AJAX issue a while back here:

CROSS DOMAIN AJAX REQUEST WITH JSON RESPONSE FOR IE,FIREFOX,CHROME, SAFARI – JQUERY

The easiest way to handle this if you have control of the responding server is to add a response header for:

Access-Control-Allow-Origin: *

This will allow cross domain AJAX. In PHP you'll want to modify the response like so:

<?php header('Access-Control-Allow-Origin: *'); ?>

you can just put Header set Access-Control-Allow-Origin * setting on apache conf or htaccess file it just work like a charm

Important Note:
The wildcard is going to allow any domain to send requests to your host. I recommend replacing the asterisk with a specific domain that you will be running scripts on.




回答2:


You can't do this with a browser unless the education.com server is configured to allow CORS (Cross-Origin Resource Sharing) requests (That's the Access-Control-Allow-Origin bit).

Your server could make the request on your behalf, however, and you can then retrieve the data from there.




回答3:


In ZF1 can be done as below:

  public function indexAction() {
    $turnkey = array(
        "uris" => array("176.x.x:3478", "3478"),
        "username" => "my_username",
        "password" => "my_password"
    );

    $content = Zend_Json::encode($turnkey);
    $this->getResponse()
            ->setHeader('Access-Control-Allow-Origin', "*")
            ->setHeader('Content-Type', 'application/json')
            ->setBody($content)
            ->sendResponse();
    exit;
  }



回答4:


Not so much a solution to the problem, but a hack to avoid the problem -- start your browser without web-security:

in MacOS this would work as follows: cd to ../../Applications/Google\ Chrome.app/Contents/MacOS
then start the brwoser with the appropiate flag: Google\ Chrome --disable-web-security'

Note: Never use the browser for normal surfing, this is just to get you going in cases of emergencies! Cheers



来源:https://stackoverflow.com/questions/17160071/xmlhttprequest-cannot-load-is-not-allowed-by-access-control-allow-origin

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