2016-07-29 109 views
1

我有一个JavaScript数组,其值为“正确”,“错误”。 我想用ajax将这个数组发送到我的php文件。但我不熟悉如何。 这是我迄今为止尝试过的。我想在没有jQuery的情况下做到这一点。通过ajax发送javascript数组而不使用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(); 

} 

回答

2

这里是通过AJAX发送JSON字符串与POST的一个示例:

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); 

避免发送JSON串用GET方法,因为我如果请求字符串太长,浏览器会给你一个错误。

现在,在你的PHP脚本,你将有$ _ POST

编辑的所有数据:看起来像在一些版本的PHP,有其他Content-type的请求,比如application/json中,$ _ POST有一个空值。要解决这个问题,你可以这样做:

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

谢谢。你能帮我用php脚本检索吗? –

+0

您应该拥有$ _POST中的所有数据,就像您通过普通表单发送数据一样。如果您不确定变量包含什么,您可以随时使用print_r($ _ POST)打印它的内容;' – Ibrahim

+0

我尝试使用print_r($ _ POST);但它只打印'array()'。而已。 –

0

替换此线

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

xmlhttp.open("GET","result.php?res="+jsonString,true); 
+0

它仍然表示'res'未定义。而且当我在php中显示数组时,它显示为空 –

+0

你的意思是你在php脚本中得到了undefined。 – atul

+0

这是我在我的php脚本中使用的**'$ res = json_decode(stripslashes($ _ GET ['res'])); echo json_encode($ res);'** –