简体   繁体   中英

Why doesn't my script accept characters?

In my SQL the echo $row['ans'] are type varchar(11): JAN,FEB,MAR,APR. I do know now why it won't be displayed out, but when I change JAN,FEB,MAR,APR into numbers it works. Please impart you knowledge and understanding to me. Thanks!

choice box

  var months = [<?php echo '"'.implode('","',explode(",",$rows['ans'])).'"'; ?> ];
  months.sort( function() { return Math.random() - .5 } );
  for ( var i=0; i<4; i++ ) {
    $('<div>' + months[i] + '</div>').data( 'months', i ).appendTo( '#monthPile' ).draggable( {
      //containment: '#content',
      stack: '#monthPile div',
      cursor: 'move',
      revert: true
    } );
  }

Create the slots

  var slot = [<?php echo '"'.implode('","',explode(",",$rows['ans'])).'"'; ?> ];
  for ( var i=0; i<=3; i++ ) {
    $('<div>' + slot[i] + '</div>').data( 'months', i ).appendTo( '#monthSlots' ).droppable( {
      accept: '#monthPile div',
      hoverClass: 'hovered',
      drop: handleCardDrop
    } );
  }

}

When injecting strings into javascript you need to put "" around those characters to tell that its a string. Your numbers work because with out the "" javascript interprets those characters as numbers. Try using the php implode function to add double quotes around your strings in the array (this is assuming $row['ans'] holds an array)

Update working example:

<?php
$rows = array(
    "ans" => "JAN,FEB,MAR"
);
?>
<html>
<body>
<script type="text/javascript">
    var test = [<?php echo '"'. implode('","',explode(",",$rows['ans'])) . '"'; ?>];
    document.write(test.toString());
</script>
</body>
</html>

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