JavaScript diceRoller仅适用于Chrome


JavaScript diceRoller only works in Chrome

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

链接到托管代码的地方:http://coldrepublic.com/diceRoller(1).html

代码:

PHP

<?php 
if(!empty($_POST['data']))
    { $data = $_POST['data']; 
    $file = 'log.txt';
    // Open the file to get existing content
    $current = $data;
    // Append a roll to the file
    $current .= file_get_contents($file);
    // Write the contents back to the file
    file_put_contents($file,$current);
}
else{
    $file = 'log.txt';
    // Open the file to get existing content
    $current = "No Value sent'n";
    // Append a new person to the file
    $current .= file_get_contents($file);
    // Write the contents back to the file
    file_put_contents($file, $current);
}

?>

Javascript/HTML

<!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>

我还没有注意到你的代码做了什么,但我想我知道问题是什么,如果我的解决方案是正确的,我将添加一些关于你的代码的其他想法。

你的代码在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)...