【问题标题】:How can I pass data from client to server use raw AJAX?如何使用原始 AJAX 将数据从客户端传递到服务器?
【发布时间】:2017-03-16 12:45:36
【问题描述】:

您好,我已经搜索过了,但他们经常使用 jquery ajax 将数据从 js 传递到 PHP(服务器端)。但是对于我的项目,它有一堆纯 js 代码,所以我应该使用原始 AJAX 来传递数据。

例如,如果我想发送一个值 = 13 的变量“Imgname”并想在 php 页面中回显。

这是我的尝试

<script>
    if(window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if(xmlhttp.readyState === 4 && xmlhttp.status === 200) {
                alert('send to server successfully');
            }
        };
        xmlhttp.open("POST", "test2.php", true);
        xmlhttp.send("Imgname=13");
    }
</script>

在 test2.php 中

<?php
$temp = $_POST['Imgname'];
echo $temp;   /////output should be 13
?>

但错误未定义索引:第 2 行 C:\xampp\htdocs\test2.php 中的 Imgname

【问题讨论】:

  • 试试xmlhttp.send({Imgname: 13});
  • @FrankerZ 那行不通。 send() 的参数必须是字符串或 FormData。您正在考虑$.ajax(),它将对象转换为编码字符串。
  • @Barmar 我从here拉出来的
  • 那里出了点问题。 语法部分没有显示类似send(Object data)的语法。

标签: javascript php ajax


【解决方案1】:

您需要确保发送正确的内容类型:

xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

【讨论】:

【解决方案2】:

尝试发送标头:

var http = new XMLHttpRequest();
var url = "test2.php";
var params = "Imgname=13";
http.open("POST", url, true);

http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

http.onreadystatechange = function() {//Call a function when the state changes.
  if(http.readyState == 4 && http.status == 200) {
    alert(http.responseText);
  }
}
http.send(params);

【讨论】:

  • 您的浏览器控制台是否出现任何错误?
  • 是的,那个警报。但在 test2.php 页面(其他页面)中,它无法回显 $_POST['Imgname'];
  • 您在哪里询问是否需要提交按钮?如果您正在加载我的 x.html,它会自动提交并仅显示 die('
    '.print_r($_POST, 1));
    以证明 Imgname 确实是由上面的 sn-p 发送的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-05
  • 1970-01-01
  • 2017-05-13
  • 1970-01-01
相关资源
最近更新 更多