jQuery重定向传递数组

On my site, users choose colors they want and after making their selections they proceed to the next page. Currently, every time they click on a color, I add it to a JavaScript array. When they are ready to go to the next page, I want to pass this array of colors so I can display their chosen colors on the next page. So my question is how can I accomplish this with jQuery or PHP?

Thanks.

You can pass the array in this way:

$.post('URL_Of_Next_Page', {'MyArray': actualArray});

To do the redirect, then you can do this:

window.location.replace("URL_Of_Next_Page");

I am not sure, but if you do the post before the redirect, then it might have the array, but I doubt it. You can either store the array in a session variable or you can do as safarov suggested and pass it via query parameters.

For the session approach

$_SESSION['MyArray'] = json_encode(actualArray);

Then to get it back:

actualArray = json_decode($_SESSION['MyArray']);

To get it JSONified to use as a string:

var actualArrayAsString = JSON.stringify(actualArray);

You can definitely pass parameters along in a query string. Looks like Justin has a good idea. For my personal approach to web applications, there are three ways I would consider doing this:

  1. Session variables in PHP. A quick search should give you the functions you need to store session variables. Super easy. If you need them back into JavaScript on the next page, you can just PHP echo them out into JS variables or better yet, use logic on the server to populate the classes or a style tag into your markup.

  2. Cookies. Cookies have worked for years and will continue to work for years to come. ;-)

  3. localStorage. Only useful if your end-users are definitely using modern browsers since localStorage is an HTML5 API. By coincidence, I wrote a little post about localStorage last night: http://gregpettit.ca/2012/fun-with-html5-localstorage-api/ (the article has links to another useful Stack Overflow post as well as an external tutorial)

If you do something client-side, you could implement #3 with a fallback to #2. If you're using #1 I wouldn't bother with a fallback because it is then server-side.