简体   繁体   English

如何在URL中传递数组以通过JavaScript检索?

[英]How can I pass an array in a url to be retrieved by javascript?

I am trying to pass an array in a url so I tried this: 我试图在URL中传递数组,所以我尝试了以下方法:

?question_id=10&value=1&array=["Saab","Volvo","BMW"]

This didn't work (didn't think it would, but it's a start). 这没有用(没想到会这样,但这只是一个开始)。

It's a key and value array anyway so I needed something like this: 无论如何,这是一个键和值数组,所以我需要这样的东西:

&array[28]=1&array[9]=1&array[2]=0&array[28]=0

But that didn't work either 但这也不起作用

in jquery try this 在jQuery中尝试这个

var arr = [1, 4, 9];
var url = '/page.php?arr=' + JSON.stringify(arr);
window.location.href = url;

If you want to pass an array, you just have to set the different parts of the array in the URI like 如果要传递数组,只需在URI中设置数组的不同部分,例如

http://example.com/myFile.php?cars[]=Saab&cars[]=volvo&cars[]=BMW

So you get your formated array in $_GET['cars'] 因此,您可以在$_GET['cars']获取格式化的数组

print_r($_GET['cars']); // array('Saab', 'Volvo', 'BMW')

To get such a result in javascript you can use this kind of code 为了在javascript中获得这样的结果,您可以使用这种代码

var cars = ['Saab', 'Volvo', 'BMW'],
    result = '';

for (var i = cars.length-1; i >= 0; i--) {
    results += 'cars[]='+arr[i]+'&';
}

results = results.substr(0, results.length-1); // cars[]=BMW&cars[]=Volvo&cars[]=Saab

Try to pass like this 尝试这样通过

?question_id=10&value=1&my_array=Saab,Volvo,BMW

and you can get like 你会得到像

<?php
    $my_array = explode(',',$_GET['my_array']);
?>

or you can try like this 或者你可以这样尝试

$aValues = array('Saab','Volvo','BMW');
$url = 'http://example.com/index.php?';
$url .= 'aValues[]=' . implode('&amp;aValues[]=', array_map('urlencode', $aValues));

You may also try this: 您也可以尝试以下方法:

?arr[]="Saab"&arr[]="BMW"

Using the jQuery getUrlParam extension I can get url variables very easily 使用jQuery getUrlParam扩展,我可以很容易地获取url变量

or in PHP 或在PHP中

var_dump($_GET);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM