If there is a large list of variable values that are obtained from other files through ajax and then assigned to many variables in js, is there any good way?
Pass the return value in the PHP file to the two variables of js,
The two variables in the obtained js file are:
bo_count=3
and
hd_count=3
PHP code<?PHP
//Generate a json string. For this, you can consider the json_encode function that comes with PHP, or you can google an open source PHP json class.
$return = "";
?>
<script type='text/javascript'>
var content = eval("(<?PHP echo $return;?>)");//$return here is equivalent to the string returned by the server after ajax is sent
for(var i in content){
window[i] = content[i];
}
alert(bo_count);//123
alert(hd_count);//456
</script>
window['abc'] = 1;
It is equivalent to setting the global variable abc equal to 1. This is not important. What is important is that after eval the json string, you can read the value according to the way js accesses the object properties, and get whatever value you want.
JScript code<script type='text/javascript'>
var content = {
bo_count: 123
hd_count: 345
}
alert(content['bo_count']);
</script>
The efficiency of json string is quite high. The previous interactive method using xml format was much more troublesome to parse.
file.PHP should write
echo 'bo_count='.$bocount=count($bo_array[0]);
echo "n";
echo 'bd_count='.$bocount=count($bo_array[0]);
In this way, the value of contents in js is "bo_count=3nbd_count=3"
It can also be like this
file.Writing in PHP
echo 'bo_count='.$bocount=count($bo_array[0]);
echo ";";
echo 'bd_count='.$bocount=count($bo_array[0]);
In this way, the value of contents in js is "bo_count=3;bd_count=3"
In short, legal js statements must be passed through ajax
Then write in js
success:function(contents) {
eval(contents);
}
Use json variables, this method I have tried repeatedly.
JScript code
function(data){
var myjson='';
eval('myjson=' + data + ';');
}