在Javascript中嵌入PHP不起作用

I've got this javascript code:

$(document)
   .load(function(){
      $.post(
          'result_source.php?term='+<?php echo $_REQUEST['term']; ?>
        );alert('abc123');
});

and it doesn't alert('abc123');. If I remove the

+<?php echo $_REQUEST['term']; ?>

it does alert('abc123').

Thanks

You need to take the PHP part out of the concatenation. The PHP is effectively pasted in to the javascript page before it is processed, so unless your $_REQUEST['term'] is the name of a javascript variable you are using, it will cause errors.

Change it to: $(document).load(function(){$.post('result_source.php?term=<?php echo $_REQUEST['term']; ?>');alert('abc123');});

Bear in mind this won't work inside external javascript files, unless you create an .htaccess or something to configure the server so it parses .js files as PHP before outputting to the browser

PHP will not run in an external JavaScript file unless you create a .htaccess file or configure the server so it parses .js files as PHP before outputting to the browser.

If you put that in a file(with a .php extension), in <script> tags, it will work, though.