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

3

您好。

我正试图从一个php文件(manage.php)向另一个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"未定义。

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


只使用 jQuery,不要混用 Xhhtp 和 ajax,让你的生活变得困难。 - user7601056
@Breakermind 如果你只需要进行 AJAX 请求,那么 jQuery 就有很多额外的开销。 - doublesharp
我不喜欢 Ajax :) 但我知道它可以上传图片。 - user7601056
我只喜欢使用jQuery语法。 - user7601056
你在 print_r($_POST) 或者 print_r($_REQUEST) 的输出中看到了吗? - doublesharp
显示剩余10条评论
2个回答

10

您的输入不完整。所以我在下面做了一个完整的示例,您可以遵循。我写了一个名为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;
?>

它起作用了 var ajax = new XMLHttpRequest();ajax.onload= success; ajax.onerror = failure; ajax.open("POST", "handle.php", true); ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); let data = 'name='+'zeeshan'; ajax.send(data);function success() { if(this.status===200) document.getElementById('demo').innerText = this.responseText; }function failure(exception) { document.getElementById('demo').innerText = exception; } - Zeeshan Mehdi

-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中的数据可以通过多种方式收集,例如序列化和使用new FormData(form)等快速方法。


1
这里使用的是jQuery,与“XMLHttpRequest”的问题无关。 - doublesharp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接