【问题标题】:$_POST empty, sending form values with Ajax$_POST 为空,使用 Ajax 发送表单值
【发布时间】: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


【解决方案1】:

您需要将内容类型设置为 application/x-www-form-urlencoded 以使值显示在 $_POST 中。

例如xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");(如果使用XMLHttpRequest 对象)。

【讨论】:

  • 他还必须发送值。
  • 我注意到在发布答案后:)
【解决方案2】:

根据答案,这是我想出的:

var xmlHttp = getXMLHttp(); // returns a new XMLHttpRequest or ActiveXObject

function Save() {
  if(xmlhttp) { 
    xmlhttp.open("POST","insert.php",true); 
    xmlhttp.onreadystatechange  = handleServerResponse;

    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');    
    xmlhttp.send("idclient=" + document.getElementById("idclient").value  
                + "&total=" + document.getElementById("total").value); 
  }
}

function handleServerResponse() {
   if (xmlhttp.readyState == 4) {
     if(xmlhttp.status == 200) {
        alert("responseText= " + xmlhttp.responseText);
        document.getElementById("btnSave").value = "Saved";
        document.getElementById("result").innerHTML = xmlhttp.responseText; 
     }
     else {
        alert("Error during AJAX call. Please try again");
     }
   }
   else{
    document.getElementById("btnSave").value = "Saving...";
   }
}

经过一段时间的搜索,我发现将这个函数定义为单独的函数(而不是像原始问题中那样在 onreadystatechange 中内联)可以让它工作。

xmlhttp.onreadystatechange  = handleServerResponse;

不过,@Daren 对“特殊”输入值提出了很好的意见。例如,在字符串字段中传递“&”字符会得到不完整的值。

【讨论】:

  • 奇怪,你怎么还支持 IE5.5 和 IE6,因为 IE7+ 版本有原生 XMLHttpRequest 对象 =P .. 不好的复制粘贴?另外,我不应该说您可以避免发送内容类型标头 IF 您没有使用 $_POST 超全局来读取值,而是手动处理输入。
【解决方案3】:

为你的表单试试这个:

<form action="javascript:Save();return false;" method='POST'>
    <p><b>Client:</b><input id='client' type='text' name='idclient'/> 
    <p><b>Total:</b><br /><input id='total' type='text' name='total'/> 

    <p><input type='submit' value='Save' id="btnSave"/>
    <input type='hidden' value='1' name='submitted' /> 
</form> 

然后像这样拨打电话:

    xmlHttp.open("POST", "insert.php", true);
    var postStr = "idclient=" + document.getElementById("client").value + "&total=" + document.getElementById("total").value;
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
      xmlHttp.send(postStr);

【讨论】:

  • 如果您的输入字段中没有 a-z0-9,这将停止工作,并且不会以一致的方式工作。我再次建议您使用 .serialize() 函数为您处理 urlencoding 混乱的 Jquery。
  • 谢谢,我将您的回答作为一个很好的起点。我只需要为onreadystatechange事件分配一个函数,否则它会挂起并且无法完成。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-27
  • 2015-02-27
  • 1970-01-01
  • 1970-01-01
  • 2013-09-24
相关资源
最近更新 更多