首页 > 解决方案 > 在 $.ajax 调用中构建 jquery url

问题描述

我正在尝试进行 $.ajax 调用并将一些数据发送到 php 文件,我的 php 文件位于

组件的文件夹和我的 js 文件在 webroot 文件夹中,如何使 $.ajax 的 url 部分指向正确的 php 文件,要从 JS 文件中获取 php 文件,我需要执行以下操作

../../../src/Controller/Component/AuthComponent.php

但是当我在 $.ajax 调用中做同样的事情时

    $.ajax({
            type: 'POST',
            url: '../../../src/Controller/Component/AuthComponent.php' ,
            data: "accessToken" + access_token, 
            dataType: 'json',
            complete: function (response) {
                console.log("data coming back from Auth.php" +response);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log(errorThrown);
            }  
   });

我只得到

http://localhost:8765/src/Controller/Component/AuthComponent.php- 404 未找到

如何构建网址?

标签: javascriptphpjqueryajax

解决方案


如果您使用的是框架或者您自己构建了路由,则适用于网站的所有其他页面。然后与那些类似,您必须为添加到 AuthComponent.php 中的 method() 创建(分配)一个新路由,例如:

Route: http://localhost:8765/authcomponent/method_name
Pointing to: /src/Controller/Component/AuthComponent.php::methodName()

然后,您的最终 JavaScript 代码将如下所示:

$.ajax({
        type: 'POST',
        url: 'http://localhost:8765/authcomponent/method_name' ,
        data: "accessToken" + access_token, 
        dataType: 'json',
        complete: function (response) {
            console.log("data coming back from methodName() of AuthComponent.php file" +response);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(errorThrown);
        }  

});


推荐阅读