简体   繁体   English

如何在多个文件上使用 Ajax 请求?

[英]How can i use Ajax request on multiple files?

I have a JavaScript file called newsletter_init.js and it makes an Ajax request.我有一个名为newsletter_init.js的 JavaScript 文件,它发出一个 Ajax 请求。

I add this JS file to every .php on my project and the issue here.我将此 JS 文件添加到我的项目中的每个 .php 以及此处的问题。

For example I use newsletter_init.js in my index.php and a URL for the ajax request will be res/ajax/request_newsletter.php .例如,我在index.php使用newsletter_init.js ,ajax 请求的 URL 将是res/ajax/request_newsletter.php

Ok, that's working but when I add the same JS file on another directory for example adding newsletter_init.js on a index.php but placed on blog folder the URL will be invalid as it will search for ../res/ajax/request_newsletter.php instead of res/ajax/request_newsletter.php .好的,这是有效的,但是当我在另一个目录上添加相同的 JS 文件时,例如在index.php上添加newsletter_init.js但放在博客文件夹中时,URL 将无效,因为它将搜索../res/ajax/request_newsletter.php而不是res/ajax/request_newsletter.php

File structure about the scope:关于范围的文件结构:

index.php
blog > index.php

I have another way to do this:我有另一种方法来做到这一点:

  1. Add content of newsletter_init.js on every file and change url but this is not a good way to approach this.在每个文件上添加 newsletter_init.js 的内容并更改 url 但这不是解决此问题的好方法。

  2. I have tried to use __DIR___ in PHP but i don't understand how to use it in this situation.我曾尝试在 PHP 中使用__DIR___但我不明白在这种情况下如何使用它。

  3. I have tried $(location).attr(pathname);我试过$(location).attr(pathname); in jQuery but it return the fild name also for example localhost/homepage/index在 jQuery 中,但它也返回 fild 名称,例如 localhost/homepage/index

  4. I can't use a direct url as i will change from localhost to my site so, i need a dynamic way.我不能使用直接 url,因为我将从本地主机更改为我的站点,因此,我需要一种动态方式。

Just ensure your path is relative to the root directory.只需确保您的路径相对于根目录。

/res/ajax/request_newsletter.php

Not:不是:

res/ajax/request_newsletter.php

If you don't add the first slash, it will try to find that path starting in the directory where you are making the call (ie wherever your current PHP script is running).如果您不添加第一个斜杠,它将尝试从您进行调用的目录(即当前运行 PHP 脚本的任何位置)开始查找该路径。

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

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