Angularjs $http load data from local disk issue in

2019-08-17 04:20发布

问题:

Angularjs, angular-1.2.0-rc.2

$http.get("gridData.json")
        .success(function(data, status, headers, config){
            angular.extend($scope.model.entities, data.entities);
        })
        .error(function(data, status, headers, config){
            alert("x");
        });

This code runs perfectly fine when load the page from server, or when run the page on local disk using firefox or chrome. But when load the page from disk in IE9 (didn't test in other IE version), it always go to error function. When debugging, when error happen, the data, status, headers all are undefined, except config has content.

Anyone have any idea? Could be any solution?

回答1:

it is due to same origin policy You would see same error in chrome. Chrome and IE does not allow local ajax requests. there are ways to do that for example chrome you would have to start it with some special flags

http://joshuamcginnis.com/2011/02/28/how-to-disable-same-origin-policy-in-chrome/

C:\Users\YOUR_USER\AppData\Local\Google\Chrome\Application\chrome.exe --allow-file-access-from-files --disable-web-security

and in ie you can reduce your security settings to be minimal.

there are other solutions like jQuery $.ajax run as a local HTML file avoiding SOP (same origin policy)

use jquery's

$.support.cors = true;

Another Solution
try to put the json data in js file or your server that way you don't have to do any ajax request to local file

Other sources:
Ways to circumvent the same-origin policy
http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/