使用XMLHttpRequest将JavaScript变量传递给PHP

4

我遇到了一个问题,无法将JavaScript变量发布到PHP文件中。请问有人能告诉我出了什么问题吗?

// Get Cookies
var getCookies = document.cookie;
cookiearray  = getCookies.split(';');

SelectedIds = cookiearray[0];

//take key value pair 

 name = cookiearray[0].split('=')[0];
 value = cookiearray[0].split('=')[1]; // The variable(values) i want to pass

// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();

hr.open("POST", url, true);
var url = "page.php";

hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
    if(hr.readyState == 4 && hr.status == 200) {
        var return_data = hr.responseText;
        document.getElementById("Comp").innerHTML = return_data;
    }
}

hr.send(value); // Request - Send this variable to PHP
document.getElementById("Comp").innerHTML = "loading...";

PHP

 $test = $_POST['value'];
 print_r($test); // NULL

谢谢


我认为你输出的不是数组,而是字符串,请尝试使用echo。 - paka
你检查了发送的实际帖子正文吗?var url = "page.php"这一行应该在引用url之前。(上面一行) - marekful
@Marcell - 是的,但它不起作用... 无论如何感谢。 - Awena
2个回答

2

代替

 print_r($test);

使用 echo
 echo $test;
$test不是一个数组,而是一个字符串值。使用print_r打印数组。这就是为什么给出了空值的原因。
而你在ajax中的发送函数应该像这样:
hr.send("value="+value);

在 send 函数中,传递的参数必须像这样是一个字符串:
"name=value&anothername="+encodeURIComponent(myVar)+"&so=on"

这里有更多的教程。


太棒了!我需要添加"value="+value。非常感谢您的解释。 - Awena

0

我已经尝试了一段时间,想要将我在JavaScript中格式化的非常长的字符串传递到PHP中保存到文件中,现在我认为我有了答案。至少对我来说可以工作。

变量'str'在被格式化后从另一个函数传递到'getGame'中。由于该字符串可能非常长,因此我使用'POST'方法。 代码如下:

    function getGame(str){
    //Sends data to the php process "save Game".
    var test = str;
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "saveGame.php", true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    
    xhr.onreadystatechange = function() {
        if (this.readyState === 4 ){
            alert(xhr.responseText);
        }
    };
    xhr.send("data="+ test); 
}

这将“data”发送到“saveGame.php”,在以下代码中将其保存到文件中,并在警报下拉菜单中返回消息。

<?php
$outputString = $_POST["data"];
$fp = fopen("C:\\xampp\\htdocs\\BowlsClub\\GamesSaved\\test26.txt","w");
if (!$fp){
    $message = "Error writing to file. Try again later!" ;
}else{
    fwrite($fp, $outputString);
    $message = "File saved!"; 
}
fclose($fp);

echo $message;
?>

这对我很有效,希望对其他新手也有用。


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