javascript - 带有输入参数的 Javascript/PHP 中的 XMLHTTP 请求

标签 javascript php ajax xmlhttprequest

我正在用这个把头撞到墙上。我的问题的答案应该是herehere ,而且我不想重复发布。但由于某种原因,我的代码虽然看起来与这些示例完全相同,但却无法工作。

我正在尝试通过 xmlhttprequest 将 ID 从 Javascript 函数传递到 PHP 函数。这是我的 Javascript 函数:

function acceptRequest(id_Request)
{
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "acceptRequest.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.onreadystatechange = function()
{
    if (xhttp.readyState == 4 && xhttp.status == 200)
    {
        alert("Request accepted.");
    };
};
xhttp.send("id_Request="+id_Request);
}    

我的 PHP 文件,acceptRequest.php,看起来像这样:

<?php
echo $_POST['id_Request'];
?>

所发生的情况是,Javascript 函数确实发送了警报:“请求已接受。”但是,PHP 函数不会回显任何内容。我在这里缺少什么???

最佳答案

我猜问题是你的函数没有传递任何 id。我确定你的 php/javascript.您要传递的 id 在某个输入框中。

然后在你的js函数中,你可以说

Var id = document.getElementById("id-of_input").value;

然后您可以将其附加到您的 Ajax 请求中。

我还注意到您的 Ajax 没有从 php 得到响应。

 if(xmlhttp.readyState == 4 &&.      xmlhttp.status == 200){
   document.getElementById(where).innerHTML = xmlhttp.responseText;

}

在你的例子中,它是 xhttp.responseText;

该行仅表示您希望在何处显示 Ajax 请求的结果。

关于javascript - 带有输入参数的 Javascript/PHP 中的 XMLHTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37202060/

相关文章:

javascript - 如何解决phonegap中的HTTPS问题

javascript - 如何在 Bootstrap 标签输入中使用谷歌音译API?

javascript - 使用axios创建post请求后,header值在服务器端返回null

javascript - React Native 性能缓慢

php - 如何在laravel中执行多个where with or查询

php - 如何使用 Twitter API 收藏推文

php DOMDocument 如何将节点值转换为字符串

JavaScript/jQuery : Divs not changing background color on loop

python - Selenium : Better method to check for AJAX changes other than an infinite loop

javascript - Rails 4 - ajax 不起作用,我需要刷新页面