我想在 JavaScript 中声明两个存储在 file.txt
中的对象,并在代码中使用它。
例如,我在我的 index.php
中写了这个:
var counter = Number(localStorage.getItem('rans')) || 0;
var counter1 = Number(localStorage.getItem('bans')) || 0;
$('.redanswer').one('click', function(){
localStorage.setItem('rans', ++counter);
$( '.rtotal' ).text( counter + " concordano" );
$( '.btotal' ).text( counter1+ " non concordano");
$('.rgraphic').css("height", counter * 100 / (counter1+counter));
$('.bgraphic').css("height", counter1 * 100 / (counter1+counter) );
});
$('.blueanswer').one('click', function(){
localStorage.setItem('bans', ++counter1);
$( '.btotal' ).text( counter1 + " concordano" );
$( '.rtotal' ).text( counter + " non concordano");
$('.rgraphic').css("height", counter * 100 / (counter1+counter));
$('.bgraphic').css("height", counter1 * 100 / (counter1+counter) );
});
如您所见,在此示例中,项目 bans
和 rans
存储在 localStorage
中,我将这些项目用于柜台。
我想编写完全相同的代码,但将新的 bans
和 rans
存储在我的 file.txt
中。我认为这必须使用 AJAX 来完成,但我不知道。
我认为file.txt必须这样写:
bans: 1; //casual number
rans: 5; //casual number
希望您能理解,非常感谢。
最佳答案
可以用ajax来完成,也可以不用ajax来完成
index.php
<?php
// read your file.txt
// strip off the comments
// get the value part of bans: 1 into a variable $bans
// get the value part of rans: 5 into a variable $rans
// for testing
$bans = 1;
$rans = 5;
echo '<script>';
echo "var master_bans = $bans;";
echo "var master_rans = $rans;";
?>
var counter = Number(localStorage.getItem('rans')) || master_bans ;
var counter1 = Number(localStorage.getItem('bans')) || master_rans;
$('.redanswer').one('click', function(){
localStorage.setItem('rans', ++counter);
$( '.rtotal' ).text( counter + " concordano" );
$( '.btotal' ).text( counter1+ " non concordano");
$('.rgraphic').css("height", counter * 100 / (counter1+counter));
$('.bgraphic').css("height", counter1 * 100 / (counter1+counter) );
});
$('.blueanswer').one('click', function(){
localStorage.setItem('bans', ++counter1);
$( '.btotal' ).text( counter1 + " concordano" );
$( '.rtotal' ).text( counter + " non concordano");
$('.rgraphic').css("height", counter * 100 / (counter1+counter));
$('.bgraphic').css("height", counter1 * 100 / (counter1+counter) );
});
</script>
关于javascript - 如何在 javascript 中使用存储在服务器中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35228030/