我几天来一直在寻找答案,但如果我在另一篇文章中错过了答案,请告诉我。
我正在尝试进入Ajax,所以我在index.php中有一个非常简单的表单,有单独的php和javascript文件:
的index.php
<div id="ajax-test">
<form action="ajax/ajax.php" method="POST">
<textarea name="someText" id="some-text" placeholder="Type something here"></textarea>
<button type="button" onclick="loadDoc()">Submit</button>
</form>
<div id="ajax-text"></div>
</div>
main.js:
function getXMLHttpRequestObject() {
var temp = null;
if(window.XMLHttpRequest)
temp = new XMLHttpRequest();
else if(window.ActiveXObject) // used for older versions of IE
temp = new ActiveXObject('MSXML2.XMLHTTP.3.0');
return temp;
}// end getXMLHttpRequestObject()
function loadDoc() {
var ajax = getXMLHttpRequestObject();
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
document.getElementById('ajax-text').innerHTML = ajax.responseText;
console.log(ajax.responseText);
}
};
ajax.open("POST", "ajax/ajax.php", true);
ajax.send();
}
ajax.php:
<?php
print_r('\'' . $_POST['someText'] . '\' is what you wrote');
?>
每当我尝试打印时,它都会打印:“''就是你所写的” - 我错过了什么/没有做错/做得不好,不允许我访问someText的内容?我已经改变了我的命名约定,从单引号换成了双引号,尝试了GET而不是POST,但没有任何效果。
答案 0 :(得分:2)
您可以尝试设置标头请求,并将数据放入发送中。这里的例子就像 -
ajax.open("POST", "ajax/ajax.php", true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.send("someText="+document.getElementById('some-text').value);
答案 1 :(得分:1)
这可能是因为错误
Undefined index: someText in C:\xampp\htdocs\ssms\sandbox\ajax\ajax.php on line 3
您的代码存在一些问题,我现在没有时间列出。这应该可以正常工作,而且我使用onkeyup()函数来显示文本,甚至没有点击提交按钮。
索引档案
<div id="ajax-test">
<form method="POST" onsubmit="return false;">
<textarea onkeyup="loadDoc()" name="someText" id="someText" placeholder="Type something here"></textarea>
<button type="button" onclick="loadDoc()">Submit</button>
</form>
<div id="ajax-text"></div>
</div>
<script type="text/javascript" src="main.js"></script>
主要Javascript文件
function _(x) {
return document.getElementById(x);
}
function ajaxObj ( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200) {
return true;
}
}
function loadDoc() {
var someText = _("someText").value;
var ajax = ajaxObj("POST", "ajax/ajax.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_('ajax-text').innerHTML = ajax.responseText;
console.log(ajax.responseText);
}
}
ajax.send("someText="+someText);
}
PHP AJAX文件
if(isset($_POST['someText'])){
$someText = $_POST['someText'];
echo "\"$someText\"" . ' is what you wrote';
exit();
} else {
echo "An error occured";
exit();
}