Ajax 调用 php 脚本返回 404 错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5760538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:24:18  来源:igfitidea点击:

Ajax call to php script returns 404 error

phpjqueryajaxwordpresshttp-status-code-404

提问by mobi

I'm a WordPress designer, I developed a contact form for one of my themes that's validated via jQuery.

我是一名 WordPress 设计师,我为我的一个主题开发了一个联系表单,该表单已通过 jQuery 验证。

Please check the code below, then read the notes beneath.

请检查下面的代码,然后阅读下面的注释。

$('.submitemail') .click(function() {

    //VALIDATION CODE GOES HERE

    if ( /*VALIDATED SUCCESSFULLY*/ ) {


        $.ajax({
            type: 'POST',
            url: templatePath+'/lib/scripts/sendEmail.php',
            data: 'visitorname=' + visitorname + '&visitoremail=' + visitoremail + '&visitormessage=' + visitormessage,

            success: function(contactResults) {
                //SUCCESS CODE
            }

        });
    }
});

Notes:

笔记:

  • sendEmail.php is a correct script that sends email using PHPmailer class.
  • templatePath variable has the value of the full template path which looks like this: http://somedomain.com/wp-content/themes/themename
  • The jQuery code above is located in lib/scripts/jfunctions.js (same directory of the php script)
  • The whole process (ajax and php) works perfectly as expected in many servers, (tested in two servers by me and other servers by my theme users).
  • sendEmail.php 是一个正确的脚本,它使用 PHPmailer 类发送电子邮件。
  • templatePath 变量具有完整模板路径的值,如下所示:http: //somedomain.com/wp-content/themes/themename
  • 上面的jQuery代码位于lib/scripts/jfunctions.js(与php脚本同目录)
  • 整个过程(ajax 和 php)在许多服务器上都按预期完美运行,(我在两台服务器上测试,我的主题用户在其他服务器上测试)。

The Problem:

问题:

In SOME servers, the success handler is not triggered while the ajax call to sendEmail.php is actually passed successfully and the php script is processed and email is sent.

在某些服务器中,当对 sendEmail.php 的 ajax 调用实际成功传递并处理 php 脚本并发送电子邮件时,不会触发成功处理程序。

When I check with firebug to see why the success handler is not triggered, firebug shows "not found 404 error", It's like a false alarm.

当我检查 firebug 以查看未触发成功处理程序的原因时,firebug 显示“未找到 404 错误”,这就像误报。

Possible causes:

可能的原因:

I think some servers is configured to block such ajax calls.

我认为某些服务器配置为阻止此类 ajax 调用。

What might be the cause for this weird issue? How to fix it?

这个奇怪的问题可能是什么原因?如何解决?

Thanks in advance.

提前致谢。

@nowk: sendEmail.php code is:

@nowk:sendEmail.php 代码是:

<?php 
// Code for loading WordPress environment goes here //

$themeName_optionTree = get_option('option_tree');

$name = trim($_POST['visitorname']);
$email = $_POST['visitoremail'];
$message = $_POST['visitormessage'];


$site_owners_email = $themeName_optionTree['owner_email'];
$site_owners_name = $themeName_optionTree['owner_name'];
$email_subject = $themeName_optionTree['email_subject'];
$success_message = '<p class="success-box">' . $themeName_optionTree['success_message'] . '</p>';

if (strlen($name) < 2) {
    $error['name'] = 1; 
}

if (!preg_match('/^[a-z0-9&\'\.\-_\+]+@[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
    $error['email'] = 1;    
}

if (strlen($message) < 2) {
    $error['message'] = 1;
}

if (!$error) {

    require_once('PHPMailer_v5.1/class.phpmailer.php');

    $mail = new PHPMailer(true);

    try {
        $mail->From = $email;
        $mail->FromName = $name;
        $mail->Subject = $email_subject;
        $mail->AddAddress($site_owners_email, $site_owners_name);
        $mail->Body = $message;
        $mail->Send();
        echo $success_message;
    } catch (phpmailerException $e) {
        echo '<p class="warning-box">' . $e->errorMessage() . '</p>';
    } catch (Exception $e) {
        echo '<p class="warning-box">' . $e->getMessage() . '</p>';
    }
}
?>

Please note that the above code executes perfectly even when ajax returns 404, weird huh!.

请注意,即使ajax返回404,上面的代码也能完美执行,很奇怪吧!。

回答by Rudie

Since the server sends a 404 (for god knows what reason), there are two ways to fix/circumvent this:

由于服务器发送 404(天知道是什么原因),有两种方法可以解决/规避此问题:

  1. Ignore the HTTP response code and change successto completein the jQuery ajax call, so that the handler is executed when the request is done no matter the server response. You know the server response (it always works). The HTML should still be available in the jQuery completehandler.
  2. Overwrite the 404 that something sends on the server (probably something Wordpress) by executing (before printing any output): header('HTTP/1.1 200 OK'). Since the script is executed, this will overwrite the crazy 404 and jQuery will receive that 200 and execute the successhandler.
  1. 忽略 HTTP 响应代码并在 jQuery ajax 调用中更改successcomplete,这样无论服务器响应如何,在请求完成时都会执行处理程序。您知道服务器响应(它始终有效)。HTML 应该在 jQuerycomplete处理程序中仍然可用。
  2. 覆盖404的东西通过执行服务器(可能是一些WordPress的)上发送(之前打印任何输出): header('HTTP/1.1 200 OK')。由于脚本被执行,这将覆盖疯狂的 404,jQuery 将收到 200 并执行success处理程序。

You could try both =) I'm pretty sure the first one will work (but that's not so clean). I'm also pretty sure the 2nd will work, but I don't know Wordpress well enough to make promises =)

你可以同时尝试=)我很确定第一个会起作用(但这不是那么干净)。我也很确定第二个会起作用,但我不太了解 Wordpress,无法做出承诺 =)

回答by Greg Tatum

I'm guessing it's because Wordpress already has an AJAX mechanism built in and it stops you from implementing it on your own. This page explains how to add AJAX to plugins:

我猜这是因为 Wordpress 已经内置了 AJAX 机制,它阻止您自己实现它。本页介绍了如何将 AJAX 添加到插件中:

http://codex.wordpress.org/AJAX_in_Plugins

http://codex.wordpress.org/AJAX_in_Plugins

Here's a snippet from the page:

这是页面的一个片段:



Ajax on the Administration Side

管理端的 Ajax

Since Ajax is already built into the core WordPress administration screens, adding more administration-side Ajax functionality to your plugin is fairly straightforward, and this section describes how to do it.

由于 Ajax 已经内置到核心 WordPress 管理屏幕中,因此向插件添加更多管理端 Ajax 功能非常简单,本节将介绍如何执行此操作。

Here's a short example. All this will be in one file.

这是一个简短的例子。所有这些都将在一个文件中。

First, add some javascript that will trigger the AJAX request:

首先,添加一些将触发 AJAX 请求的 javascript:

<?php
add_action('admin_print_scripts', 'my_action_javascript');

function my_action_javascript() {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {

    var data = {
        action: 'my_action',
        whatever: 1234
    };

    // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
    $.post(ajaxurl, data, function(response) {
        alert('Got this from the server: ' + response);
    });
});
</script>
<?php
}

Then, set up a PHP function that will handle that request:

然后,设置一个处理该请求的 PHP 函数:

<?php 

    add_action('wp_ajax_my_action', 'my_action_callback');

    function my_action_callback() {
    global $wpdb; // this is how you get access to the database

    $whatever = intval( $_POST['whatever'] );

    $whatever += 10;

    echo $whatever;

    die(); // this is required to return a proper result
}

That's it! You will need to add a few details, such as error checking and verifying that the request came from the right place ( using check_ajax_referer() ), but hopefully the example above will be enough to get you started on your own administration-side Ajax plugin. NOTE: Since Version 2.8, The javascript global variable ajaxurl can be used in case you want to separate your javascript code from php files into javascript only files. This is true on the administration side only.

就是这样!您需要添加一些细节,例如错误检查和验证请求是否来自正确的位置(使用 check_ajax_referer() ),但希望上面的示例足以让您开始使用自己的管理端 Ajax 插件. 注意:从 2.8 版开始,如果您想将 javascript 代码从 php 文件分离为仅 javascript 文件,可以使用 javascript 全局变量 ajaxurl。这仅适用于管理方面。

回答by Amit

As seen here https://cooltrainer.org/fixing-false-404-headers-on-external-pages-including-wp-blog-header-php/this solution tested and works well:

如此处所示https://cooltrainer.org/fixing-false-404-headers-on-external-pages-包括-wp-blog-header-php/该解决方案经过测试且运行良好:

require_once("path/to/wp-config.php");
$wp->init();
$wp->parse_request(); 
$wp->query_posts();
$wp->register_globals(); 
$wp->send_headers();

回答by Cthos

Without digging into the problem, you might check that the ajax request is actually going where you think it is going. There could be several things going on here, such as the server is set up to redirect any requests to /wp-content/ somewhere else.

在不深入研究问题的情况下,您可能会检查 ajax 请求是否真的去到了你认为要去的地方。这里可能有几件事情发生,例如服务器被设置为将任何请求重定向到 /wp-content/ 其他地方。

Capture some header information using firebug, and perhaps livehttp headers.

使用 firebug 捕获一些标头信息,也许还有 livehttp 标头。