2017-06-03 71 views
0

发送var数组从html到php的最佳方式是什么? 我尝试过使用serialise,但它似乎没有正常工作。 感谢如何发送var数组从html到php

//HTML 
var arrayTextAreasNames = ['1','2','3']; 
xhttp.open("GET", "MyPhpScript.php?hId=" + inputId + "&arrayTextAreasNames=" + serialize(arrayTextAreasNames), true); 
//Note: along with the array I am also sending another variable called inputId 

//PHP 
$arrayTextAreasNames = unserialize($_GET["arrayTextAreasNames"]); 
console.log($arrayTextAreasNames); //The array is not read properly in php (empty!) 
+0

如何POST方法解码JSON纽约。在PHP中使用'print_r($ array)'或'var_dump($ array)'而不是'console.log' –

+1

'console.log'不能在php中工作。它用于javasctipt – Saty

回答

0

你必须做在Javascript中的两个步骤,你可以添加arrayString。

  1. stringify object:它必须是HTTP GET到服务器的字符串。
  2. 对有效URI进行编码:对合法URI字符串进行编码。

var arrayTextAreasNames = ['1','2','3']; 
 
var jsonstring = JSON.stringify(arrayTextAreasNames); 
 
console.log('before encode, ', jsonstring); 
 

 
var encoded = encodeURIComponent(jsonstring); 
 
console.log('encoded, ', encoded); 
 

 
/// xhttp.open("GET", "MyPhpScript.php?hId=" + inputId + "&arrayTextAreasNames=" + encoded, true);

在PHP(Live demo here), 然后,您可以解码回你期望的字符串。

$uri = '%5B%221%22%2C%222%22%2C%223%22%5D'; 
$result= urldecode($uri); 
0

这是肮脏的,但也许是这样的:

var arrayString = ""; 

for (int i = 0; i < varArray.length; i++) 
{ 
    arrayString += "&element" + i + "=" + varArray[i]; 
} 

然后到你URL

0

使用JSON.stringify只需将您的阵列成JSON和使用encodeURIComponent

var arrayTextAreasNames = ['1','2','3']; 
var jsonString = JSON.stringify(arrayTextAreasNames); 

xhttp.open("GET", "MyPhpScript.php?hId=" + inputId + "&arrayTextAreasNames=" + encodeURIComponent(jsonString), true); 

通过它,在你的PHP使用rawurldecode

$arrayTextAreasNames = json_decode(rawurldecode($_GET['arrayTextAreasNames']));