简体   繁体   中英

Javascript Objects & arrays to server through form (json/??) - best practices

I would like to know what would be the best practice to perform this:

  1. Based on a selection, create a list of "selected items" which would be a list of this kind:

      {items {categoryString {tag_id1 {[fr]=>itemFR, [en]=>itemEN} {categoryString {tag_id2 {[fr]=>item2FR, [en]=>item2EN} {categoryString2 {tag_id3 {[fr]=>item3FR, [en]=>item3EN} } 
  2. Send this information to my server script when sending my form (not through javascript but normal post form).

  3. Parse the received information on my server script (PHP).

Point 1 is done like this:

function initTagArray(listSelector) {
    var et_tag_list = new Object();
    var cat = "CATDEF";
    et_tag_list[cat] = new Object();

    listSelector.each(function() {
        et_tag_list[cat][$(this).val()] = [];
        et_tag_list[cat][$(this).val()]['fr'] = [$(this).text()];
        et_tag_list[cat][$(this).val()]['en'] = [$(this).text()];
    });

    return et_tag_list;
}​

Point 2 : I was thinking about storing that information in JSON array, but not sure how... By parsing my object/array and manually creating the json array?

Point 3 : If Json array is sent it will be easy to parse it.

I'm looking here for the best practices on how to do this the most clean way as possible.

Try JSON.stringify on those objects. You will find lots of articles in the internet about how stringify works. For example try this: https://developer.mozilla.org/En/Using_native_JSON .

You can stringify complex JavaScript objects (say x ) if you define toJSON function on it (probably you would implement in in such a way that it will gather data in the form of simple js dictionary and then you will call JSON.stringify(data) on it) and then call JSON.stringify(x) .

Use json stringified object/data that is either parsed as follows:

var myJSONObject = {"bindings": [
        {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},
        {"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},
        {"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}
    ]
}

var myJSONText = JSON.stringify(myJSONObject );

you can look for these links for implementation etc:
check question text on this link : json object accessing
JSON in JavaScript
JSON.Stringify
pass json object to array - autocomplete
Create a JSON serialized object to make a $.postJSON call

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