如何 ajax 发布到重写的 url

How to ajax post to a re-written url?

本文关键字:重写 url ajax 如何      更新时间:2023-09-26

目前我正在通过post向PHP文件提交表单,唯一的问题是我无法提交到该php文件,因为ajax出了问题。我的问题是,如果后端重写了 URL,我可以提交到其他 URL 吗?

当前页面网址: - 实际:http://site.com/topic.php?id=1 - 改写:http://site.com/topic/1

想要的页面网址: - 实际:http://site.com/comment.php

如何发送到评论.php文件?我认为javascript假设我正在尝试做 site.com/topic/comment.php

.HTML:

            <form id="comment_on_topic" onsubmit="return sendComment();">
            <textarea id="topicreply" name="topicreply">Initial value.</textarea>
            <input type="submit" name="submit" value="submit" />
        </form>

Javascript:

function sendComment(){
        var $form = $('#comment_on_topic');
        var $inputs = $form.find("input, select, button, textarea");
        var serializedData = $form.serialize();
        $inputs.prop("disabled", true);
        /* GET FORM INPUTS & SERIALIZE */
        var http = new XMLHttpRequest();
        http.open("POST", '/comment.php');
        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        http.send(serializedData);
        /* AJAX REQUEST TO POST TO FILE */
        return false;
    }

PHP://根本没有被执行。(评论.php)

    <?php if($_SERVER['REQUEST_METHOD'] == "POST") : ?>
<?php
    require_once 'protected/connect.inc.php';
    require_once 'protected/functions.inc.php';

    $comment = sanitize($_POST['topicreply']);
    sendComment( 1, 1, "Topic Reply", $comment );
?>
<?php endif; ?>

是的,JavaScript正在执行。序列化数据看起来不错("id=value&otherid=value")

要了解会发生什么,我建议:- 查看 Apache 日志(访问和错误),以查看您的 URL 是否被重写以及如何重写。- 要运行,请从浏览器或Chrome插件Postman等工具手动查询(然后您可以看到PHP错误)。

这应该有助于发现问题!

我已经解决了这个问题。我不得不使用 http.open( "POST", '../评论.php' );JavaScript/html/CSS 不会在实际的文件路径(如 PHP)上选取。(只是将来对其他人的帮助)