通过XMLHttpRequest将数据从JavaScript发送到PHP

时间:2017-03-29 16:00:56

标签: javascript php ajax xmlhttprequest

美好的一天。

我正在尝试将一个简单的数据从一个php文件(manage.php)发送到另一个(view.php)。

我无法通过表单发送数据,我想通过JS脚本发送它。这是我的尝试:

var read = function(id) {
  xmlhttp = new XMLHttpRequest();

  xmlhttp.open("POST", "view.php", true);
  xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlhttp.send("id=" + id);
}

在view.php中,使用$ _POST [“id”]会导致错误,指出索引“id”未定义。

发送数据的正确方法是什么?谢谢。

2 个答案:

答案 0 :(得分:2)

您的输入不完整。所以我做了下面的完整示例,你可以遵循。我创建了一个名为readid(id)的函数,可以根据需要执行相同的操作。然后我在需要时从html调用该函数。

<!doctype html>
<html lang="fr">
<head>
<meta charset="iso-8859-1">
<title>Untitled Document</title>
<script type="text/javascript" charset="iso-8859-1">
function readid(id){
"use strict";   
console.log("id=", id)
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/cgi-bin/view.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
    if (this.readyState === 4 || this.status === 200){ 
        console.log(this.responseText); // echo from php
    }       
};
xmlhttp.send("id=" + id);
}
</script>
</head>
<body>
<p>This is a test</p>
<input type="button" name="Submit" value="Submit" id="formsubmit" onClick="readid(id)">
</body>
</html>

view.php

<?php
$logFile = "view.log";
$id = $_POST['id'];
file_put_contents($logFile, $id);
echo $id;
?>

答案 1 :(得分:-1)

        <!DOCTYPE html>
    <html>
    <head>
      <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    </head>
    <body>
        <form id="formoid" title="" method="post">
            <div>
                <label class="title">First Name</label>
                <input type="text" id="name" name="name" >
            </div>
            <div>
                <label class="title">Name</label>
                <input type="text" id="name2" name="name2" >
            </div>
            <div>
                <input type="submit" id="submitButton"  name="submitButton" value="Submit">
            </div>
     </form>
    <script type='text/javascript'>
        /* attach a submit handler to the form */
        $("#formoid").submit(function(event) {

          /* stop form from submitting normally */
          event.preventDefault();

          $.ajax({
    type: 'POST',
    data: id,
    url: 'PATH_TO_VIEW.PHP',                        
    success: function(data) {
        //do something 
    },
    error: function(data){
        console.log('Something went wrong.');
    }
});
        });
    </script>

    </body>
    </html> 

现在可以收集许多例如ajax中的数据。序列化和新的FormData(表单)快速命名两个。