我有一个 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/