dqrl3595 2013-02-13 09:39
浏览 46

用PHP常量重构jQuery

This is a clarification and advice question. From building an application I have come to refactor much of my jQuery from the <head> tags into its own .js files. My contention is that I'm using constants to define paths.

Therefore if I refactor code that needs those PHP constants then the jQuery code will not work, because as far as I know I cannot include the init.php file that contains the constants. Am I mistaken? is there a way to include the needed Constants within my jQuery files for code such as the type below:

$.ajax({
    type: "POST",
    url: "<?php echo SITE_PATH; ?>file.php"
});

The above code is a snippet from a jQuery AJAX POST, which works fine within my head. But if I was to refactor the code to its own JS file how would I go about getting access to the desired constants and using them within JS?

Any thoughts would be appreciated.

  • 写回答

1条回答 默认 最新

  • dongxiane0395 2013-02-13 09:43
    关注

    Just pass the routes through your object params. I would suggest the following, it gets more organized and it is also easier to use Closure Compiler or other tools that affect the JS later.

    on a .js file:

    function myObj(obj){
       var routes = (obj && obj.routes) || {};
    
       $.ajax({
        type: "POST",
        url: routes.file
       });
    }
    

    on your html:

    myObj({ routes: { file: "<?php echo SITE_PATH; ?>file.php" } });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog