在 cakePHP 中调用 ajax 时使用操作 url 的最佳实践 [英] best practice to use action url while calling ajax in cakePHP
问题描述
我在 cakePHP 应用程序中使用 ajax 和 jQuery.
我的 javascript 函数放在一个 javascript 文件中.
I am using ajax with jQuery in my cakePHP application.
and my javascript function is placed inside a javascript file.
现在在我的本地系统中,文件保存在/sample"目录中,因此我调用该函数时的路径为
now in my local system the files are kept in "/sample" directory so the the path while i call the function will be
在 ajax.js 中
in ajax.js
$.post({url : "/sample/controller/action"})
但在托管后,网址将变为
but after hosting it the url will become
$.post({url : "/mydomain.com/controller/action"})
在cakePHP中我们$html->url
来生成urls
但由于此代码在 js 文件中,我无法使用该功能
in cakePHP we $html->url
to generate urls
but since this code is in js file i can't use that function
我不想在托管之前手动更改所有 ajax 操作 url
推荐答案
要做的是在蛋糕应用的主模板中创建一个可以在整个应用程序中使用的全局 javascript 变量.在执行任何 JS 包含之前,请确保它存在.
What to do is in your master template for your cake app create a global javascript variable that can be used throughout your application. Make sure it exists befor you do any JS includes too.
<head>
...
<script type="text/javascript">var myBaseUrl = '<?php echo $html->url; ?>';</script>
...
<script type="text/javascript" src="mycustomJSfile.js">
...
</head>
现在,您可以从 MVC 框架应用程序中的任何视图文件中执行此类操作.
Now you can do things like this from any view file you have in your MVC framework app.
$.post({url: myBaseUrl + 'controller/action'});
这篇关于在 cakePHP 中调用 ajax 时使用操作 url 的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!