简体   繁体   中英

Remove comma from jQuery array

Problem:

I have an array in JS that looks like this:

["intelligence", "skin", "weight", "volume"]

This is stored in a var called "newListASource". I apply this var to a form and then submit it using POST.

// Form destination
var formUrl     = 'explorer.php',

// Generate the form
$form = $("<form action='"+ formUrl +"' method='post'></form>")
        .append("<input type='hidden' name='Perspective' value='" + newListASource + "'>")
        .append("<input type='hidden' name='form_submitted' value='true'>")
        .appendTo('body');

// Submit the form
$form.submit();

When I pick it up through PHP and print it out, it gives me a string with commas. For instance:

skin,weight,intelligence,volume

Desired output I would like is (with trimmed spaces in the beginning and end):

skin weight intelligence volume

由于您使用的是数组,因此将Array.join()与分隔符一起使用为' '

"<input type='hidden' name='Perspective' value='" + newListASource.join(' ') + "'>"

newListASource.join(' ') will give you the desired result -

// Generate the form
$form = $("<form action='"+ formUrl +"' method='post'></form>")
    .append("<input type='hidden' name='Perspective' value='" 
        + newListASource.join(' ') + "'>")
    .append("<input type='hidden' name='form_submitted' value='true'>")
    .appendTo('body');

// Submit the form
$form.submit();

See the doc .

Currently you are getting comma separated values because newListASource.toString() is called whenever you are concatenating your array with a string, and this is the default behavior of toString method for arrays. When you call join , however, it converts your array to a string, separated by the delimiter that you pass to it as argument. So you get values separated by spaces in this case.

使用.join()

newListASource.join(' ')

You can use .join() and $.trim() :

// Form destination
var formUrl     = 'explorer.php',
    newListASource = newListASource.join(' ');

then in the form you can change to this:

$.trim(newListASource)  
 var arr = ["intelligence", "skin", "weight", "volume"];


 var result = ary.join(',');

就像那样:

arr.join("")

What you can also do is just send the array as an array!

var formUrl     = 'explorer.php';
var $form = $("<form action='"+ formUrl +"' method='post'></form>")
    .append("<input type='hidden' name='form_submitted' value='true'>")
    .appendTo('body');
while(newListASource.length)
    $form.append($("<input type='hidden' name='Perspective[]' value=''>").val(newListASource.shift()));
$form.submit();

Php will then actually have an array inside $_POST['Perspective'] . (Beware the input name is now Perspective to indicate it will be an array.) ,表示它将是一个数组。)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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