AJAX code do not run locally

2019-01-29 08:32发布

Code to read subfolders is given below

function countFolder(){
    var dir='albums';
    var count=0;
    alert(dir);
    $.ajax({
        url: dir,
        async:false,
        success: function (data) {
            $(data).find("a:contains(" + 'album' + ")").each(function () {// function to read foldera name contains 'album'
                count++;
                //alert(url);
            });
        }
    });
    return count;
}

This code runs perfectly when I use it on localhost. But it does not run when run locally(i.e. from file location) . I have 12 sub-folders. So when I use localhost I get the output of 12, however when run locally I only get the output of 0.

What would be the problem? Please help me.. I am new with jQuery. So if it is my mistake please notify it. In code I only use html, jQuery, js, but not php.

2条回答
在下西门庆
2楼-- · 2019-01-29 08:36

Ajax makes a call to the server. When you open from localhost, the page opens with help of a server (xampp or tomcat). But when you open the page from the file location, it just displays the static content, only html and js, but not any server side code. Even php code will not work if you open from file location

查看更多
男人必须洒脱
3楼-- · 2019-01-29 08:49

This is because of Browsers cross-domain policy. You can't send ajax request outside the domain from which the request have been send. So basically, you can't use ajax locally at all.

查看更多
登录 后发表回答