ajax 请求在本地主机 wampserver 中不工作

ajax request not working in localhost wampserver

我有以下代码

$.ajax({
        url: "../profile/companyAutocomplete.php",
        type: "GET",
        data: dataQuery,
        dataType: "json",
        success: function(responseData) {
            companySelectHandler(responseData);
        }
    });

我在生产服务器中被调用时没有任何问题。但是当我在我的本地系统中使用它时,ajax 请求没有发出。我在所有浏览器中都试过了,但还是一样。导致问题的原因是什么?我需要为此打印 ajax 错误消息。我怎样才能做到这一点?

最常见的问题是尝试在本地主机上错误地访问页面。

使用 WAMP、XAMPP 等,您不能只在地址栏中键入:c:\website\index.php

相反,您必须输入:localhost

查看此答案了解更多信息:

您应该使用 URL 而不是相对路径,例如 url: "http://localhost/something/profile/companyAutocomplete.php".

也可以省略域名,以“/something/profile/companyAutocomplete.php”开头。

感谢您的回答。不是因为相对 URL 引用。

我使用以下函数找出导致 Ajax 请求失败的错误。

$(function() {
    $.ajaxSetup({
        error: function(jqXHR, exception) {
            if (jqXHR.status === 0) {
                alert('Not connect.\n Verify Network.');
            } else if (jqXHR.status == 404) {
                alert('Requested page not found. [404]');
            } else if (jqXHR.status == 500) {
                alert('Internal Server Error [500].');
            } else if (exception === 'parsererror') {
                alert('Requested JSON parse failed.');
            } else if (exception === 'timeout') {
                alert('Time out error.');
            } else if (exception === 'abort') {
                alert('Ajax request aborted.');
            } else {
                alert('Uncaught Error.\n' + jqXHR.responseText);
            }
        }
    });
});

该错误是一个解析错误,由于浏览器在返回 JSON 之前试图打印其他内容而生成。它是通过在输出 JSON 之前使用 ob_start 和 ob_end_clean 修复的,它通过从以下 link “dataType: "json" won't work”[=12] 获得帮助来清除缓冲区=]

由于本地主机和服务器之间的配置差异,它可能会在“http://localhost:port/path/file.php" instead of "http://localhost:port/webapproot/path/file.php". Changing your Ajax call in local host prepending web app name in relative path might resolve if it was the issue. Usually on hosting servers "/file.php" refers to application's root and so no issue, but it could be possible in local host that it may be looking at local server root by default since configuration. Better always to use relative path "/webappname/path/file.php", however use "http://127.0.0.1:port/webappname/path/file.php”处查找本地主机,这比在本地 URL 中使用 "localhost" 更快。