Search code examples
javascriptphp.htaccessurl-rewritingxmlhttprequest

Using a specific URL in XMLHttpRequest, return NetworkError: A network error occurred


var xmlhttp = new XMLHttpRequest;
if (!xmlhttp) {
    alert ("XMLHttpRequest create error");
}
xmlhttp.open ("GET", "http://127.0.0.10/advert/123", false);
xmlhttp.onreadystatechange = function () {

    if (xmlhttp.readyState == 4) {
        console.log (xmlhttp.status);
        if (xmlhttp.status == 200) {
            console.log (xmlhttp.responseText);
        } else {
            alert ("Error");
        }
    }
};
xmlhttp.send ();

The specific URL is '//host/advert/???'. Like:

//127.0.0.12/advert/123

//127.0.0.12/advert/test

And more...

Only using like this Url, Mistakes will come up.

The specific URL env is PHP+APACHE(rewrite), Code like this:

index.php

echo 123;
exit;

.htaccess

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]

Solution

  • You're mixing usage of synchronous and asynchronous requests.

    If you're passing false as 3rd parameter to open method, meaning that request should be synchronous (why, btw?), then you should process it like this:

    xmlhttp.open("GET", "http://127.0.0.10/advert/123", false);
    xmlhttp.send(null);
    
    if (xmlhttp.status === 200) {
      console.log(xmlhttp.responseText);
    }
    

    Additional information: Synchronous and asynchronous requests