简体   繁体   中英

code works on localhost but not live server

My code works perfectly fine on localhost. However, when I copied and pasted the exact same code on my live server I got this error message: Failed to load resource: the server responded with a status of 404 (). I checked my folder path and it looks correct to me. I don't know what is wrong here.

var folder = "image/";
$(document).ready(function () {
    $.ajax({
        url: folder,
        success: function (data) {
         console.log("successful load")
            $(data).find("a").attr("href", function (i, val) {
                if (val.match(/\.(jpe?g|png|gif)$/)) {
                      theImageList.push(folder + val );
            };
        })
            left_show_image(theImageList[shuffledComparison[0][0]],window.innerWidth/10*4.88, screen.width/3, "left")
            right_show_image(theImageList[shuffledComparison[0][1]],window.innerWidth/10*4.88, screen.width/3, "right")\
        },
        error: function(){
            alert("cannot read your folder")
        }
    })
})

This is really confusing to me and I would appreciate any advice.

You need to fix the folder path. Try adding the slash before image:

var folder = "/image/";

OR

var folder = "~/image/";

Also place this inside of the document.ready function

$(document).ready(function () {
 var folder = "/image/";
    $.ajax({
        url: folder,
        success: function (data) {
        console.log("successful load")
        $(data).find("a").attr("href", function (i, val) {
            if (val.match(/\.(jpe?g|png|gif)$/)) {
                  theImageList.push(folder + val );
        };
    })
        left_show_image(theImageList[shuffledComparison[0]
[0]],window.innerWidth/10*4.88, screen.width/3, "left")
        right_show_image(theImageList[shuffledComparison[0]
[1]],window.innerWidth/10*4.88, screen.width/3, "right")\
    },
    error: function(){
        alert("cannot read your folder")
    }
}) 
})

This will use the base url and then search for the image folder so it should work for both local host and on the server. Also, make sure you have uploaded your image folder to the server

Using relative paths in javascipt may cause 404 error when deploying web site under a virtual or root directory.

image folder should work with both virtual or root directory. you provide a variable for application path such as appUrl.

var appUrl = 'localhost or live server root folder'

var folder = appUrl + "/image";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM