Is the following code correct?
$.ajax( {
url: './ajax/aj开发者_运维技巧ax_addTerms.php',
type: 'POST',
data: {"fId" : $fId, "term" : $term, "alias" : $alias,
"userId" : <?php print $userId; ?>},
When I remove the PHP tags it works, but this way it doesn't.
Wrap the value like this:
"userId" : "<?php print $userId; ?>"}
Otherwise JS will try to parse the PHP output which is wrong.
$.ajax( {
url: './ajax/ajax_addTerms.php',
type: 'POST',
data: {"fId" : <?php echo $fId ?>, "term" : "<?php echo $term ?>", "alias" : "<?php echo $alias ?>",
"userId" : <?php echo $userId; ?>},
// echo is faster than print
// and I assume $fId and $userId are integers so quotes aren't required
PHP's interpreter will parse variables and then JS does the rest.
I would use json_encode
additionally to the <?php ?>
to make sure that " in a string gets escaped properly:
data: {"fId" : <?php echo json_encode($fId); ?>, "term" : <?php echo json_encode($term) ?>, "alias" : <?php echo json_encode($alias); ?>, "userId" : <?php echo $userId; ?>},
This way, you could also pass an array:
<?php $data = array('fId' => $fId, 'term' => $term, 'alias' => $alias, 'userId' => $userId); ?>
...
data: <?php echo json_encode($data); ?>, // Same result as above
JavaScript is client side, PHP is server side. Ajax works like this,
JavaScript HTTP request --> PHP --> return request that is catched by the Ajax handler.
You can't start Ajax from the server side.
精彩评论