JavaScript diceRoller仅适用于Chrome

时间:2015-08-31 17:41:57

标签: javascript php google-chrome browser

以下代码仅适用于谷歌浏览器,如果我尝试使用任何其他浏览器,它就不会工作。我怀疑它与我发送给php的数据类型有关。但是,我并不完全确定。

指向代码托管位置的链接:this

代码:

PHP

<!DOCTYPE html>
<html>
<head>
<style>

#CharacterLabel {margin-right:110px}
#ActionLabel {margin-right:125px}
#NumOfDiceLabel {margin-right:60px}
#SidesLabel {margin-right:20px}

</style>
</head>
<body onload="myFunction()">
<p><label id="CharacterLabel" for="CharacterInput">Character:</label> 
<label id="ActionLabel" for="ActionInput">Action:</label>
<label id="NumOfDiceLabel" for="NumDice">Number of Dice:</label>
<label id="SidesLabel" for="Sides">Sides:</label>
<label id="BonusLabel" for="BonusInput">Bonus:</label></p>
<p><input type="text" name="Character" id="CharacterInput" />
<input type="text" name="Action" id="ActionInput" />
<input type="text" name="NumberOfDice" id="NumDice" />
<select id="Sides">
	<option value="3">d3</option>
	<option value="4">d4</option>
	<option value="6">d6</option>
	<option value="8">d8</option>
	<option value="10">d10</option>
	<option value="12">d12</option>
	<option value="20" select="selected">d20</option>
	<option valoue="100">d100</option>
</select>
<input type="text" name="Bonus" id="BonusInput" /></p>
<p><button onclick="rollDice()" style="width:100px; height:50px;">Roll Dice</button></p>
<p><textarea name="Output" id="OutputBox" rows="10" cols="100" readonly="true"/></textarea></p>
<label id="ErrorLog">Message:</label>

<script>

function getXMLHttpRequestObject(){
	var ajaxWork=null;
	if(window.XMLHttpRequest){
		ajaxWork = new XMLHttpRequest();
	}
	else if (window.ActiveXObject){
		ajaxWork = new ActiveXObject('MSXML2.XMLHTTP.3.0');
	}
	return ajaxWork;
}

function callAjax(ajaxWork)
{
	ajaxWork.open('GET', 'http://coldrepublic.com/log.txt', true);
	ajaxWork.send(null)
}

function writeToLog(toLog)
{
	var data = new FormData();
    	data.append("data",toLog);
	
	var xhr = getXMLHttpRequestObject();
	xhr.open( 'POST', 'http://coldrepublic.com/writeToLog.php', true );

	xhr.send(data);
}

function myFunction(){

	var ajaxWork = getXMLHttpRequestObject();

	ajaxWork.onreadystatechange = function(){
		if(ajaxWork.readyState == 4){
			if((ajaxWork.status >=200 && ajaxWork.status < 300)
			|| (ajaxWork.status == 304)){
				document.getElementById('OutputBox').value = ajaxWork.responseText;
			
			}
			else{
				document.getElementById('ErrorLog').innerHTML = "Message: Error! Did not properly read file";
			}
		}
	}
	
	callAjax(ajaxWork);
}

function rollDice(){
	var character = document.getElementById("CharacterInput").value;
	var action = document.getElementById("ActionInput").value;
	var sides = parseInt(document.getElementById("Sides").value);
	var diceRolls = "";
	var toLog = "";
	
	var OutputBox = document.getElementById('OutputBox');

	document.getElementById('ErrorLog').innerHTML = 'Message:';

	var bonusBlank = document.getElementById("BonusInput").value;

	if(character == null || character == "",action == null || action == "")
	{	

		document.getElementById('ErrorLog').innerHTML = 'Message: Error! Must enter value for Character or Action.';
	}
	else
	{
		if(isInt(parseInt(document.getElementById("NumDice").value)) && isInt(parseInt(document.getElementById("BonusInput").value)))
		{
			var numDice = parseInt(document.getElementById("NumDice").value);
			var bonus = document.getElementById("BonusInput").value;

 			for (i=0; i < numDice; i++)
			{
				var numTemp = Math.floor(Math.random() * sides) +1;
				var strTemp = numTemp.toString();
				diceRolls = diceRolls.concat(" " + strTemp);
			}
		
			var outTemp = "";
			var outTemp = outTemp.concat();
			var dateTemp = timeStamp();
			
			toLog = character + " " + action + " " + diceRolls + " Bonus: " + bonus + " Timestamp: " + dateTemp + "\n" ;
			writeToLog(toLog);
			location.reload();
			location.reload();
		}
		else
		{
			if(bonusBlank == null || bonusBlank == "")
			{
				var numDice = parseInt(document.getElementById("NumDice").value);
				var bonus = 0;

 				for (i=0; i < numDice; i++)
				{
					var numTemp = Math.floor(Math.random() * sides) +1;
					var strTemp = numTemp.toString();
					diceRolls = diceRolls.concat(" " + strTemp);
				}
		
				var outTemp = "";
				var outTemp = outTemp.concat();
				var dateTemp = timeStamp();
				
				toLog = character + " " + action + " " + diceRolls + " Bonus: " + bonus + " Timestamp: " + dateTemp + "\n";
				writeToLog(toLog);
				location.reload();
				location.reload();
			}
			else
			{
				document.getElementById('ErrorLog').innerHTML = 'Message: Error! Entered non-integer value for Number of Dice or Bonus.';
			}
		}
	}
}

function isInt(value) {
  return !isNaN(value) && 
         parseInt(Number(value)) == value && 
         !isNaN(parseInt(value, 10));
}

function timeStamp(){
	// Create a date object with the current time
  	var now = new Date();

	// Create an array with the current month, day and time
  	var date = [ now.getMonth() + 1, now.getDate(), now.getFullYear() ];

	// Create an array with the current hour, minute and second
  	var time = [ now.getHours(), now.getMinutes(), now.getSeconds() ];

	// Determine AM or PM suffix based on the hour
  	var suffix = ( time[0] < 12 ) ? "AM" : "PM";

	// Convert hour from military time
  	time[0] = ( time[0] < 12 ) ? time[0] : time[0] - 12;

	// If hour is 0, set it to 12
  	time[0] = time[0] || 12;

	// If seconds and minutes are less than 10, add a zero
  	for ( var i = 1; i < 3; i++ ) {
    	if ( time[i] < 10 ) {
      		time[i] = "0" + time[i];
    	}
  }

	// Return the formatted string
  	return date.join("/") + " " + time.join(":") + " " + suffix;
	
}
</script>

</body>
</html>

&GT;

的Javascript / HTML

{{1}}

1 个答案:

答案 0 :(得分:1)

我还没有为你的代码所做的事情付出太多的注意力,但我想我知道问题是什么,如果我的解决方案是正确的,我会对你的代码添加一些其他想法。< / p>

您的代码适用于Chrome,因为Chrome的工作速度比任何其他浏览器都要快,并且能够在调用页面重新加载之前执行您的xhr调用(实际上这只是一个运气,它只是一个运气在Chrome中工作,在某些机器上,结果可能会有所不同,因此它可能在其他浏览器中工作或根本不工作)。要使其在任何其他浏览器中工作,您需要在xhr调用中添加回调并在回调内执行location.reload();

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests

function writeToLog(toLog)
{
    var data = new FormData();
    data.append("data",toLog);

    var xhr = getXMLHttpRequestObject();
    xhr.open( 'POST', 'http://coldrepublic.com/writeToLog.php', true );

    xhr.onload = function (e) {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          console.log('ok');
          location.reload();
        } else {
          console.error('problem');
        }
      }
    };

    xhr.send(data);
}

请勿忘记从location.reload();

中的其他位置移除rollDice
        toLog = character + " " + action + " " + diceRolls + " Bonus: " + bonus + " Timestamp: " + dateTemp + "\n" ;
        writeToLog(toLog);
    }

EDIT: 由于主要问题得到解决,这里有一些其他建议

character == null

这些值来自输入和输入存储字符串,因此它们永远不会是空值,只有character == ""应该足够

你在这做什么

if(character == null || character == "",action == null || action == "")

错误,您使用逗号运算符https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator而不是另一个OR||

isInt(parseInt(document.getElementById("NumDice").value)

过于宽泛parseInt会返回NaN或Number,所以

function isInt(value) {
  return !isNaN(value) && 
     parseInt(Number(value)) == value && 
     !isNaN(parseInt(value, 10));
}

毫无意义。

if (!isNaN(NaN))if (NaN)

相同

parseInt(Number(value)) == value在这里再没有意义,因为你已经将parseInt的结果传递给它(isInt(parseInt(document.getElementById("NumDice").value))

!isNaN(parseInt(value, 10));一样,如果它的数字是任意基数的数字,如果它是NaN,它总是一个NaN

if (parseInt(document.getElementById("NumDice").value)...应该足以检查输入的有效数字(0也有效,所以您可能还想添加> 0检查)

如果您想检查1是否仅从1sdfsdf转换,那么您可能想要添加

var numdice = document.getElementById("NumDice").value; 
if (numdice == parseInt(numdice)...