简体   繁体   中英

how to use PHP loop in JQuery

I have the following JQuery Function.

   <script>

    var forbiddenWords = ['Phone', 'Home', 'Address', 'Number', 'Postcode', 'email', 'call','n u m b e r'];
    $(function () {
      $('.msgbox').on('keyup', function(e) {
        forbiddenWords.forEach(function(val, index) {
          if (e.target.value.toUpperCase().indexOf(val.toUpperCase()) >= 0) {
              e.target.value = e.target.value.replace(new RegExp( "(" + val + ")" , 'gi' ), '');
          }
        });
      });
    });

    </script>

I want the words in fordiddenWords array should be dynamic and must come from MySQL database. I have written the following code but it is not working..!

     <script>

 var forbiddenWords = [<?php foreach($result as $res) { echo $res->rest_words; } ?>];
        $(function () {
          $('.msgbox').on('keyup', function(e) {
            forbiddenWords.forEach(function(val, index) {
              if (e.target.value.toUpperCase().indexOf(val.toUpperCase()) >= 0) {
                  e.target.value = e.target.value.replace(new RegExp( "(" + val + ")" , 'gi' ), '');
              }
            });
          });
        });

        </script>

The words appear like this..!

var forbiddenWords = [phonenumberaddress];

Please Help.

You can simply use json_encode function for convert php array into JSON/Javascript object or Array

var forbiddenWords = [<?php foreach($result as $res) { echo $res->rest_words; } ?>];

Replace it with

<?php
$arr=array();
foreach($result as $res) { $arr[]=$res->rest_words; }
?>
var forbiddenWords = <?php echo json_encode($arr); ?>;

OR

var forbiddenWords = <?php echo json_encode(array_map(function($record){ return $record->rest_words; }, $result)); ?>;

You're missing the commas and the quotes:

 <script>

 var forbiddenWordsString = <?php foreach($result as $res) { echo "'" . $res->rest_words . "',"; } ?>;
 var forbiddenWords = [forbiddenWords.substring(0, str.length - 1)]; // remove last comma
    $(function () {
      $('.msgbox').on('keyup', function(e) {
        forbiddenWords.forEach(function(val, index) {
          if (e.target.value.toUpperCase().indexOf(val.toUpperCase()) >= 0) {
              e.target.value = e.target.value.replace(new RegExp( "(" + val + ")" , 'gi' ), '');
          }
        });
      });
    });

</script>

Echoing like this directly in Javascript is not the correct way to pass information. It would be easier if you convert your $result array to json so it's more native for js. Try:

http://php.net/manual/en/function.json-encode.php

So it should look something like this:

var forbiddenWords = <?=json_encode($result)?>;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM