【问题标题】:Post method with ajax使用ajax发布方法
【发布时间】:2020-05-12 08:44:30
【问题描述】:

我想使用 javascript 将数据发送到另一个 php 页面,但它没有按预期工作。 假设我有表格:

<form id="myForm">
        <label for="name">Username</label>
        <input type="text" name="name" id="name">
        <label for="pass">Password</label>
        <input type="password" name="pass" id="pass">
        <button id="submit" type="submit" >OK</button>
</form>

和脚本:

   const myForm = document.getElementById('submit');

myForm.addEventListener('submit', function(e){
    e.preventDefault();

    const data = new FormData(this);

var xhr = new XMLHttpRequest();
xhr.open('POST', 'getData.php', true);
xhr.onload = function () {
    // do something to response
    console.log(this.responseText);
};
xhr.send(data);
});

php 文件目前无法接收数据。它如何用 ajax 或任何其他等效代码修复?

【问题讨论】:

  • 需要修复第一行JS;它应该获取表单,而不是提交按钮。
  • 非常感谢!但我只是测试它,它给了我 Cors 错误,这对我来说没有意义?
  • 确切的错误信息是什么?
  • @ChrisG 这是我的错,标题不应该在本地文件中。谢谢

标签: javascript ajax post


【解决方案1】:

更改按钮

<button id="submit" type="button" onclick="sendData()" >OK</button>

然后添加javascript函数。

<script>
  function sendData(){

    var name = document.getElementById("name");
    var password = document.getElementById("pass");

     if (name) {
         $.ajax({  
             type:"POST",  
             url:"path-to-php-file.php",  
             data:'name='+name+'&pass='+password,
             success:function(data){  
                alert(data);                            
             }  
      });   
  }
</script>

然后创建 php 文件,您将在其中获取数据。 path-to-php-file.php

<?php 
  $name = $_POST['name'];
  $password = $_POST['pass'];

  echo $name .'--'.$password; 
?>

【讨论】:

    【解决方案2】:

    如果不查看您的 php 代码,我无法准确判断问题所在。 可能Content-Type 标头有问题。

    document.getElementById('submit').addEventListener('submit', (e) => {
        e.preventDefault();
    
        const data = new FormData(this); // Here 'this' will not work, you gotta loop through the inputs and append them to the FormData object.
    
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = () => {
        // do something
    }
    xhr.open('POST', 'getData.php', true);
    // the default content type is application/x-www-form-urlencoded
    xhr.setRequestHeader("Content-Type", "<content type here>")
    xhr.send(data);
    });
    

    额外

    我的建议是,在您的情况下,您在这里并不需要表单元素。您可以使按钮成为普通按钮,并使表单成为 div(不是特别的好处,只是为了干净的代码)。将函数分配给按钮的onclick 事件并循环输入并将它们附加到表单数据(如果内容类型为application/x-www-form-urlencoded)对象并将其发送到服务器。如果您有复杂的情况,请使用此方法类似于 Google 或 Microsoft 的交互式表单。

    如果你按照我的方法,你也不想使用 preventDefault() 方法。

    这是大多数专业人士都会做的事情。

    【讨论】:

      猜你喜欢
      • 2021-08-23
      • 2013-11-18
      • 2021-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多