HttpRequest xhr Post使用表单变量



所以我一定是在看一些非常基本的东西。我试图发送表单数据更新mysql记录使用ajax http post请求。我有一页表格。在表单上,我有一个提交按钮,从一个单独的js文件调用http请求,js文件调用php文件。使用firebug,它看起来不像我有任何错误,但是当我"打印"请求返回的sql时,它没有传递实际的变量,它只是传递"$_POST['name']"。

返回sql:

UPDATE contacts SET name= "$_POST['name']" , phone = "$_POST['phone']" WHERE id = "$_POST['id']"

而不是传递实际的变量值。我的问题是我如何传递实际的变量数据,以便它返回类似的东西:

UPDATE contacts SET name= "Mike", phone = "303-333-3333" WHERE id = "001"

我的表单(它周围不包含表单标签)看起来像这样:

    <label>
      <input type="text" name="name" id="name" />
    </label>
    <label>
      <input type="text" name="phone" id="phone" />
    </label> 
    <label>
      <input type="hidden" name="id" id="id" />
    </label>
    <label>
      <input  onclick="sendData()"type="submit" name="button" id="button" value="Submit" />
    </label>

my js在单独的文件中看起来像:

    function sendData()
 {
if (window.XMLHttpRequest)
   {// code for IE7+, Firefox, Chrome, Opera, Safari
   xmlhttp=new XMLHttpRequest();
   }
 else
   {// code for IE6, IE5
   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }
 xmlhttp.onreadystatechange=function()
   {
   if (xmlhttp.readyState==4 && xmlhttp.status==200)
     {
     document.getElementById("center").innerHTML=xmlhttp.responseText;
     }
   }
 xmlhttp.open("POST","xhr_php/send.php",true);
 xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
 xmlhttp.send("name={$_POST['name']}&phone={$_POST['phone']}&id={$_POST['id']} ");
 }

我的send.php文件如下:

db_connection include
$name= $_POST['name'];
$phone= $_POST['phone'];
$id = $_POST['id'];
print $query = "UPDATE contacts SET 
        name = '{$name}',
        phone = '{$phone}', 
WHERE id= {$id}";
$results= mysql_query($query, $db_connection);
if(mysql_affected_rows()==1){
    echo "Success";
}
if(mysql_affected_rows()==0){
    echo "failed";
}

在调用正确的文件方面,一切似乎都正常工作,只是没有传递任何变量数据。任何帮助都将非常感激。谢谢你。

我相信错误就在这一行

xmlhttp.send("name={$_POST['name']}&phone={$_POST['phone']}&id={$_POST['id']} ");

改成这样:

var name = document.getElementById('name').value;
var phone = document.getElementById('phone').value;
var id = document.getElementById('id').value;
xmlhttp.send("name="+name+"&phone="+phone+"&id="+id);

最新更新