【问题标题】:HttpRequest xhr Post using form vaiablesHttp Request xhr Post 使用表单变量
【发布时间】:2011-11-08 02:37:17
【问题描述】:

所以我一定是在看一些非常基本的东西。我正在尝试使用 ajax http post 请求发送表单数据以更新 mysql 记录。我有一个带有表格的页面。在表单上,​​我有一个提交按钮,该按钮从单独的 js 文件调用 http 请求,并且该 js 文件调用 php 文件。使用萤火虫,看起来我没有任何错误,但是当我“打印”请求返回的 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>

我在一个单独文件中的 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";
}

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

【问题讨论】:

    标签: ajax post xmlhttprequest


    【解决方案1】:

    我相信错误就在眼前

    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);
    

    【讨论】:

    • 感谢您的帮助。那成功了,我知道这很简单。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2012-12-17
    • 2022-08-09
    • 1970-01-01
    • 2011-03-25
    • 2014-04-14
    • 1970-01-01
    • 2011-12-23
    • 1970-01-01
    相关资源
    最近更新 更多