Jump to content

Indexof() - Solved With Our Thanks In The Last Post.


niche

Recommended Posts

The first code box produces the result I expected (4). The second code box produces a -1 on what I believe is the same string (ie var txt=document.innerHTML=xmlhttp.responseText; displays "Bob , Brittany , Brian" when it's not commented out). Any ideas why? Is it possible "xmlhttp.responseText" isn't a string?

<html><body><script type="text/javascript">var str="Bob , Brittany , Brian";document.write(str.indexOf(",") + "<br />");</script></body></html>

if (xmlhttp.readyState==4 && xmlhttp.status==200) {   var div = document.createElement('div');	  div.setAttribute('id', 'link_container');	  div.setAttribute("style","background-color:white;");	  div.style.width = '300px';	  div.style.height = '100px';	 div.style.margin = '-15px 0px 0px 75px';	  //var txt=document.innerHTML=xmlhttp.responseText;	 var txt = str.indexOf(",");	 document.getElementsByTagName('body')[0].appendChild(div);	 document.getElementById('link_container').innerHTML=txt;	}

Link to comment
Share on other sites

The indexOf() method goes on the end of a string object, not on a fixed object called 'str'. (unlike String.fromCharCode)eg:

var pos = txt.indexOf(",");

I think xmlhttp.responseText will only not be a string if the readyState is not 4, or the status is not 200, even then though it could be a blank string, not sure on that.

Link to comment
Share on other sites

dooh! Code://var txt=document.innerHTML=xmlhttp.responseText; var txt=xmlhttp.responseText; var txt = txt.indexOf(","); JamesB, Don't understand.

Link to comment
Share on other sites

dooh! Code://var txt=document.innerHTML=xmlhttp.responseText; var txt=xmlhttp.responseText; var txt = txt.indexOf(","); JamesB, Don't understand.
he's trying to impart some error handling. he's saying that responseText will probably always be a string (unless the readyState is not 4, or status is not 200) but that the response could be empty, i.e. an empty string => "". However, for a custom application like this, it's probably not that big of a deal.
Link to comment
Share on other sites

Thanks Ingolme, JamesB and thescientist. Those empty strings frequently catch me off guard. I also know more about xmlhttp.responseText thanks to your help.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...