我有以下PHP代码,它返回一个数组$words
,其中包含MySql数据库中列SimplifyingFractionsQuestions
的所有单词:
<?php
$data5 = $db->query("SELECT GROUP_CONCAT(DISTINCT SimplifyingFractionsQuestions ORDER BY rand()) as SimplifyingFractionsQuestions FROM (SELECT SimplifyingFractionsQuestions FROM answers WHERE user_id=$id AND SimplifyingFractionsQuestions LIKE 's%') AS SimplifyingFractionsQuestions ")->fetch_assoc();
$selector= $data5['SimplifyingFractionsQuestions'];
$words = explode(" ", $selector);
?>
此外,我还有以下Jquery,它为该数组中的每个类添加了一个具有唯一CSS属性的新类ClassHide
<script type='text/javascript'>
$(document).ready(function () {
var arr = <?php echo json_encode($words); ?>;
jQuery.each( arr, function( i, val ) {
$( "." + val ).addClass("ClassHide");
});
});
</script>
然而,消息来源显示,它会返回:
var arr = ["Question 1, Question 2, Question 3"]
所以它只会将类ClassHide
添加到类Question 1, Question 2, Question 3
我需要它返回
var arr = ["Question 1", "Question 2", "Question 3"]
因此它会将课程ClassHide
添加到包含课程Question 1
或Question 2
或Question 3
答案 0 :(得分:1)
编辑#2
在看到数据之前,我认为这是问题所在,但似乎window.onload
将完成工作 - 但我的评论仍然是,Javascript行仍应以分号结束
json_encode()
不会这样做。你想做类似
json_encode()
编辑#1
这一行
var arr = [<?php // leading '[' starts the array definition
$sep='';
foreach ($words as $word)
{
echo $sep.'"'.$word.'"';
$sep=',';
} ?>]; // trailing ']' ends the array, don't forget the semicolon!
将尝试将$words = explode(" ", $selector);
的内容分解为数组元素,在空格($selector
)字符处分隔字符串。由于" "
中没有任何空格,$selector
将与$words
完全相同,您需要$selector
NB 您应该将单引号字符串用于静态字符串值,而不是双引号字符串,这样PHP解释器就不必解析静态字符串的内容。 (更快,更少处理开销,更好......)
答案 1 :(得分:0)
尝试这样的事情:
viewDidLoad()
和你的jquery
<?php
$data5 = $db->query("SELECT DISTINCT SimplifyingFractionsQuestions as SimplifyingFractionsQuestions FROM (SELECT SimplifyingFractionsQuestions FROM answers WHERE user_id=$id AND SimplifyingFractionsQuestions LIKE 's%') AS SimplifyingFractionsQuestions ORDER BY RAND() ")->fetch_assoc();
$selector= $data5['SimplifyingFractionsQuestions'];
foreach($data5['SimplifyingFractionsQuestions'] as $ques){
$questionarray[] = $ques;
}
?>
注意:如果两个函数都存在,则不需要
<script type='text/javascript'> $(document).ready(function () { jQuery.each( <?= $questionarray ?>, function( i, val ) { $( "." + val ).addClass("ClassHide"); }); }); </script>
相同的页面,或者从PHP传递它作为字符串并解码它 jquery与json_encode