最好的做法是使用操作URL,而在CakePHP中调用AJAX [英] best practice to use action url while calling ajax in cakePHP

查看:179
本文介绍了最好的做法是使用操作URL,而在CakePHP中调用AJAX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我使用Ajax和jQuery的在我的CakePHP的应用程序。
我的JavaScript函数放置在一个JavaScript文件。


I am using ajax with jQuery in my cakePHP application.
and my javascript function is placed inside a javascript file.

现在在我的本地系统中的文件都保存在/样本目录,这样的路径,而我调用该函数将

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

$.post({url : "/sample/controller/action"})

但托管后的网址将成为

but after hosting it the url will become

$.post({url : "/mydomain.com/controller/action"})

在CakePHP我们 $基于HTML>网址生成URL
但因为这code是在js文件我无法使用该功能。

in cakePHP we $html->url to generate urls
but since this code is in js file i can't use that function

我不想托管之前手动更改所有的Ajax动作网址

推荐答案

做的是在你的主模板为您的事业锦上添花的应用程序创建一个全球 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'});

这篇关于最好的做法是使用操作URL,而在CakePHP中调用AJAX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆