简体   繁体   English

外部js文件中的PHP基本URL

[英]PHP base URL in external js file

I have few JS in HTML page, if I use this in HTML view file then its working fine, my page submit form correctly without any issue. 我在HTML页面中有很少的JS,如果我在HTML视图文件中使用它,那么它的工作正常,我的页面正确提交表单没有任何问题。

But when I moved this JS codes to external JS file, then it shows error, 但当我将这个JS代码移动到外部JS文件时,它显示错误,

Below is my JS 下面是我的JS

$("#user_fm").submit(function (event) {
    event.preventDefault();
        $.ajax({
            type: "POST",
            url: "<?php echo base_url(); ?>index.php/admin/peoples/add_user",
            data: $("#user_fm").serialize(),
-----

my problem is clear to me, that in view page this is easily get decoded to my url 我的问题很明显,在视图页面中,这很容易被解码到我的网址

"<?php echo base_url(); ?>index.php/admin/peoples/add_user"

but when i keep this in JS file it show like below in console, 但当我把它保存在JS文件中时,它在控制台中显示如下

POST http://localhost/center/index.php/admin/peoples/%3C?php%20echo%20base_url();%20?%3Eindex.php/admin/peoples/add_user

How can we put PHP codes in JS file? 我们如何将PHP代码放入JS文件中?

To be able to embed PHP in html or javascript code, like <?php echo base_url();?> , the file must have .php extension, while your external javascript file certainly has .js extension. 为了能够将PHP嵌入到html或javascript代码中,例如<?php echo base_url();?> ,文件必须具有.php扩展名,而外部javascript文件肯定具有.js扩展名。 Besides .js files are parsed by the browser, while PHP files must be executed on the server. 除了.js文件由浏览器解析,而PHP文件必须在服务器上执行。

What you can do is to first define a variable in inline javascript, and then use it in code of external .js files. 你可以做的是首先在内联javascript中定义一个变量,然后在外部.js文件的代码中使用它。 In index.php or whatever main file you use, place this before you use your external js code: 在index.php或您使用的任何主文件中,在使用外部js代码之前放置它:

<script type="text/javascript">
var baseURL = "<?php echo base_url(); ?>";
</script>

And then in your external code: 然后在您的外部代码中:

$("#user_fm").submit(function (event) {
    event.preventDefault();
        $.ajax({
            type: "POST",
            url: baseURL + "index.php/admin/peoples/add_user",
            data: $("#user_fm").serialize(),
-----

clearly you cant access. 显然你无法访问。 Run your script with XXAMP YOU need to turn apache service on so that php can read YOUR base URL 使用XXAMP运行脚本您需要打开apache服务,以便php可以读取您的基本URL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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