2016-07-29 92 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);'** –