javascript - 通过ajax发送javascript数组而不使用jquery

标签 javascript php arrays ajax

我有一个 JavaScript 数组,其中包含“正确”、“错误”等值。 我想使用 ajax 将此数组发送到我的 php 文件。但我不熟悉如何。 这是我到目前为止所尝试过的..并且我想在没有jquery的情况下做到这一点。

var hold=[];
    for(t = 0;t <= 10; t++){ 
    answers_Arr = document.getElementsByName("question"+t);
    for (k = 0; k < answers_Arr.length; k++){
        if(answers_Arr[k].checked){
            hold[t] = answers_Arr[k].value;
            //document.getElementById("test"+t).innerHTML = "Value: "+ hold[t];
            break;
        }else{
            hold[t] = "no";
            continue;

        }
    }
}
var jsonString = JSON.stringify(hold);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
    if (xmlhttp.readyState==4  &&  xmlhttp.status==200)
    {
    document.getElementById("test1").innerHTML= xmlhttp.responseText;
    }
}

xmlhttp.open("GET","result.php?res="+hold[],true);
xmlhttp.send();

}

最佳答案

下面是通过 AJAX 使用 POST 发送 json 字符串的示例:

var jsonString = JSON.stringify(hold);
var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function() {
    //
}

xmlhttp.open("POST","result.php",true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.send(jsonString);

避免使用 GET 方法发送 json 字符串,因为如果请求字符串太长,浏览器会抛出错误。

现在,在您的 php 脚本中,您将拥有 $_POST 中的所有数据

编辑:看起来在某些版本的 php 上,具有其他 Content-type 的请求,例如 application/json,$_POST 具有空值。要解决此问题,您可以执行以下操作:

$_POST = json_decode(file_get_contents('php://input'));

关于javascript - 通过ajax发送javascript数组而不使用jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38664798/

相关文章:

php - 今天/明天而不是 x 小时内碳

php - 从另一个多维数组创建多维

javascript - 如果使用对象样式向函数添加属性会发生什么情况?

javascript - GroupBy CSV 文件中的数组元素并有助于减少代码

javascript - 当 JS 压缩器重命名变量时,如何通过 eval() 设置变量?

php - 将php变量放入mysql查询

php - Laravel hasManyThrough 操作 user_id

c++ - 将字符数组中的元素范围提取到字符串中

arrays - 如何使用指定数量的元素创建指定大小的数组的每个版本?

php - 使用 JQuery 从具有相同 POST 参数的同一 PHP 文件中得到不同的 AJAX XML 结果