簡體   English   中英

如何將var數組從html發送到php

[英]How to send var array from html to php

將var數組從html發送到php的最佳方法是什么? 我嘗試使用serialise但似乎無法正常工作。 謝謝

//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!)

它很臟,但是也許是這樣的:

var arrayString = "";

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

然后可以將arrayString添加到您的URL

您必須在Javascript中執行兩個步驟。

  1. stringify對象:必須為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( 此處為在線演示 )中,您可以解碼回所需的字符串。

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

只需使用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解碼json ny

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM