【发布时间】:2011-07-01 17:43:43
【问题描述】:
HTML
<form action='insert.php' method='POST'>
<p><b>Client:</b><input type='text' name='idclient'/>
<p><b>Total:</b><br /><input type='text' name='total'/>
<p><input type='submit' value='Save' id="btnSave"/>
<input type='hidden' value='1' name='submitted' />
</form>
PHP (insert.php)
<?php
echo file_get_contents('php://input');
include_once "connect.php";
if ($db_found){
if (isset($_POST['submitted'])) {
foreach($_POST AS $key => $value) {
$_POST[$key] = mysql_real_escape_string($value);
}
$sql = "INSERT INTO `mytable` ( `idclient` , `total` , ) " .
"VALUES( {$_POST['idclient']} , {$_POST['total']} ) ";
mysql_query($sql) or die(mysql_error());
}
}
mysql_close($db_handle);
?>
这工作正常,但是当我尝试使用 Ajax 调用插入时,$_POST 函数为空,我无法访问表单中的值。
这是ajax代码和函数调用:
<form action="javascript:Save()" method='POST'>
Ajax
function Save()
{
xmlHttp = getXMLHttp(); // returns a new XMLHttpRequest or ActiveXObject
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState == 4) {
document.getElementById("btnSave").value = "Saved";
document.getElementById("result").innerHTML = xmlHttp.responseText;
}
else{
document.getElementById("btnSave").value = "Saving...";
}
}
xmlHttp.open("POST", "insert.php", true);
xmlHttp.send(null); // Do I need to create and pass a parameter string here?
}
执行echo file_get_contents('php://input'); 确实 $_POST 是空的,并且参数值没有传递。
我可以像这样连接 URL 中的 params 值
xmlHttp.open("POST", "insert.php?idclient=123&total=43", true);
但是,有没有办法使用 $_POST 并利用它?
【问题讨论】:
-
您没有传递任何参数。并且不要将表单
action更改为javascript:...。如果 JS 被禁用,表单将不起作用。改为收听submit事件。所以是的,你必须发送值。请参阅send文档:https://developer.mozilla.org/en/XMLHttpRequest#send() -
我建议使用 Jquery,而不是自己编写代码。这将成为一个班轮。
-
同意@Daren Schwenke,无需重新发明轮子!
-
@Felix Kling 提交事件的好主意。但是,当点击提交按钮时,所有输入字段都被清除,看起来它正在重新加载页面,这是为什么呢?
-
@CarlosTorres:似乎您也在发送“正常”的 POST 请求(因此页面重新加载)。您必须阻止
submit事件的默认操作,即提交表单(显然)。您可以通过从事件处理程序返回false来做到这一点。要了解有关事件处理的更多信息,我建议阅读 quirksmode.org 上的精彩文章:quirksmode.org/js/introevents.html
标签: php javascript mysql ajax