【发布时间】:2015-08-27 08:51:05
【问题描述】:
我正在尝试将一个变量从 javascript 函数传递到我的 php 文件。我所做的就是从 javascript 中的 cookie 中提取 user_name,然后使用 AJAX 将变量 $_POST 到我的 php 文件中进行处理。我不使用表单来提交我过去所做的 POST 变量。
问题是我的 $_POST 数组没有传递给 php 文件。我看过这里并查看了其他几个建议,但没有一个工作。您是否必须通过 html 表单提交 $_POST 变量?我不这么认为,但也许我错了。代码如下:
Javascript -
function clearDoneItems() {
var user_name = getNameFromCookie();
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
alert(user_name);
xmlhttp.open("POST","todolist/clear_done_items.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(user_name);
displayHomeInformation(user_name);
}
PHP -
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Clear Done Items</title>
</head>
<body>
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
print_r($_POST);
$xml_name=$_POST['user_name'];
$xml_file = $xml_name . ".xml";
echo $xml_file;
/* Here we will use the The DOMDocument class functions to delete
the text nodes.
Format XML to save indented tree rather than one line */
$domxml = new DOMDocument('1.0');
if ($domxml->load('$xml_file') === TRUE) {
$domxml->preserveWhiteSpace = false;
$domxml->formatOutput = true;
// Start Delete process of node
echo "<br>";
$xpath = new DOMXPath($domxml);
// Here we use the The DOMXPath class function evaluate to do the heavy lifting.
foreach ($xpath->evaluate('//doneitems/item') as $node) {
$node->parentNode->removeChild($node);
}
//Save XML to file - remove this and following line if save not desired
$domxml->save('alan.xml');
echo "<strong>XML Document updated.</strong>";
}
else {
echo " <strong>Error in loading XML file:</strong>";
echo "<br>";
print_r(error_get_last());
}
?>
</body>
</html>
php页面上的错误: 注意:未定义索引:第 16 行 /var/www/bb/todolist/clear_done_items.php 中的用户名 0 警告:DOMDocument::load(): I/O 警告:未能在第 24 行的 /var/www/bb/todolist/clear_done_items.php 中加载外部实体“/var/www/bb/todolist/$xml_file”
【问题讨论】:
-
旁注:
$xml_file = $xml_name + ".xml";+是一个 JS/C++ 连接运算符。你想用一个点。请使用 HTML 表单编辑您的问题。 -
另外,如果您正在运行包括 HTML 表单和 PHP 的整个代码,您将需要使用
isset()或!empty()作为 POST 数组。很有可能,您的输入没有命名或有错字。 -
“你必须通过 html 表单提交 $_POST 变量吗?” - 很多时候,是的。
$_POST['user_name']来自哪里? -
最后评论 -
user_name似乎依赖于getNameFromCookie()所做的一切。 -
谢谢我更正了 php。我认为通过阅读 AJAX POST 变量是从三个命令 xmlhttp.open、.setRequestHeader 和 .send 设置的。这些不是代替 html 表单中的 POST 操作吗?