Ajax:尝试使用相对路径时出现 Post 错误

Ajax: Getting a Post Error when trying to use Relative Path

正在努力获取 Ajax post 请求的相对路径以获取 php 文件。我没有收到错误,只是什么也没发生。

浏览了该站点,但找不到关于 Ajax 我理解的相对路径的先前答案。这方面还是菜鸟。如果有人能通俗易懂地解释一下,我将不胜感激。

我正在尝试从根文件 'index.php' 访问 php 文件 'search/search.php'(此文件包含 Ajax 请求)。这在两个文件都在同一目录中时有效。

文件结构如下:

JQuery 代码片段:

$(function() {
  $('form').on("submit", function(e) {
    e.preventDefault();
    $('#error').text(""); // reset
    var name = $.trim($("#search").val());
    if (name.match(/[^a-zA-Z0-9 ]/g)) {
      $('#error').text('Please enter letters and spaces only');
      return false;
    }
    if (name === '') {
      $('#error').text('Please enter some text');
      return false;
    }
    if (name.length > 0 && name.length < 3) {
      $('#error').text('Please enter more letters');
      return false;
    }

    $.ajax({
      url: 'search/search.php',
      method: 'POST',
      data: {
        msg: name
      },
      dataType: 'json',
      success: function(response) {

      $(".content").html("")
      $(".total").html("")

        if(response){
          var total = response.length;
          $('.total') .append(total + " Results");
         }

        $.each(response, function() {
          $.each($(this), function(i, item) {

            var mycss = (item.Type == 1) ? ' style="color: #ffa449;"' : '';
            $('.content').append('<div class="post"><div class="post-text"> ' + item.MessageText + ' </div><div class="post-action"><input type="button" value="Like" id="like_' + item.ID + '_' + item.UserID + '" class="like" ' + mycss + ' /><span id="likes_' + item.ID + '_' + item.UserID + '">' + item.cntLikes + '</span></div></div>');
          });
        });
      }
    });
  });
});

前面的正斜杠仅表示“从文档根目录开始”,index.php 所在的位置。所以 /search/search.php 应该是正确的。如果服务器无法找到该文件,按理说必须进行一些 url 重写。

您只需将浏览器指向 http://localhost:8000/search/search.php 即可进行测试。如果你得到一个 404,你就知道它与 ajax

无关