[英]JavaScript diceRoller only works in Chrome
如果我尝试使用任何其他浏览器,则下面的代码仅适用于Google 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();
;。 内部回调。
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
检查)
如果要检查仅不是1sdfsdf
转换了1
,则可能需要添加
var numdice = document.getElementById("NumDice").value;
if (numdice == parseInt(numdice)...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.