【发布时间】: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,但我希望研究一个能够让他们轻松搞定。