简体   繁体   中英

Http Response Code from within Html/Javascript

Is it possible using Javascript/Html5 to check the http reply code for a particular web page? For example, if the user enters a sentence, I wish to check to see if I have an audio file for each word in the sentence. I realize I should use a database to lookup the availability of a word but I'm currently working on a very simple demo which currently consists of a single html file and a bunch of ogg files.

The current versions of the XHR for some time now actually have allowed one to do form submissions through them. I've been using that for a while now to do javascript RPC to MySql and it works like a champ. Of course as always XHR has that HTTP status code your looking for.

Just scope out the current docs for XMLHTTP over at the Mozilla site and you'll have that kicking like you want in no time

You could try using ajax to achieve that. Here is a simple example using the jquery ajax function:

// Assuming this is the word you are looking for
var str = "bells";

$.ajax( "www.example.com/audio/" + str + ".ogg" ).done(function () {
   // An audio file for that word exists
}).fail( function () {
   // There is no audio file for that word
});

For a whole sentence you could just split it into words and look each one up individually.

XMLHttpRequest is definitely the way to go, assuming you're not going to use a database (which I would highly recommend because they're totally awesome.)

function oggSearch () {
  alert(this.responseText);
};

var sInput = ''; //grab it from whatever element you're using
var oggReq = new XMLHttpRequest();
oggReq.onload = oggSearch;
//I'm not sure if concatenating the file type will cause issue
oggReq.open("get", sInput + ".ogg", true);
oggReq.send();

I obviously haven't tested the above, but it's based off the link below.

https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest

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