【问题标题】:Ajax post displaying an inadequate messageAjax 帖子显示不充分的消息
【发布时间】:2012-06-21 16:20:36
【问题描述】:

我是 AJAX 方法的新手。我想发布一些由 php 页面处理的信息,称之为 page.php

在我的 html 页面中,我放了这段代码:

<script type="text/javascript" charset="utf-8">
//I have put the function getXMLHttpRequest() on a separate js file
function getXMLHttpRequest() {
    var xhr = null;

    if (window.XMLHttpRequest || window.ActiveXObject) {
        if (window.ActiveXObject) {
            try {
                xhr = new ActiveXObject("Msxml2.XMLHTTP");
            } catch(e) {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
        } else {
            xhr = new XMLHttpRequest(); 
        }
    } else {
        alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest...");
        return null;
    }

    return xhr;
}

function request(callback) {
    var xhr = getXMLHttpRequest();

    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
            callback(xhr.responseText);
        }
    };

    xhr.open("POST", "page.php", true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send("name=proposition");
}

function postData(Data) {

    alert(Data);

}
</script>

<button onclick="request(postData);">...</button>

在page.php中,我有一个方法

protected function comment(){
//some code processing the posted infos (that works fine)...

//to debug, I have put a
echo('Hello world');

}

事实上,我没有收到任何“Hello world”,而是一条巨大的警报消息,其中显示了我的所有网页代码。

有人有想法吗?

最好, 纽本

【问题讨论】:

  • 考虑为你的 AJAX 使用 jQuery,它的代码更少,更容易;)
  • 说真的,我不想冒犯任何人,但我已经看过这个带有 XMLHttpRequests 的代码一百万次了,我不希望每个人都使用 jquery,但我希望研究一个能够让他们轻松搞定。

标签: php ajax post


【解决方案1】:

您在 page.php 中定义了一个函数,但从未调用它。 并删除 protected 关键字,因为它没有意义(你不是在上课)

试试

function comment(){
//some code processing the posted infos (that works fine)...

//to debug, I have put a
echo('Hello world');

}

comment();

【讨论】:

  • 其实要清楚一点:page.php的结构是page.php?page='mypage'&post='post'。所以首先有一个mypage.php的方向,和然后在 mypage.php 中有一个类的实例化。 __construct 方法使用 post 变量来调用类中的一个方法,该方法称为 comment()。这对你有意义吗?
  • 请张贴 mypage.php 的内容。这样做似乎是一种不合逻辑的方式。我愿意将所有代码放在一个文件中。
  • 您的 php 文件似乎被解释为纯文本,因此它显示在警报中。您是否忘记在任一 php 页面 ( 中添加 PHP 起始标记
  • 对不起,我不明白
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-13
相关资源
最近更新 更多