简体   繁体   中英

.ajax and params and how to get them to look like this?

I tried posting a previous question, but i believe it was convoluted.

Basically, i was told "can you make the data come thru like this?" - keep in mind that this data is not derived from a form, but but by data that is driven via a search on the client side.

This is what is suppose to be sent to the server. So if you dumped the error_log, it would look this. This is all dynamic, so the object below will be that format BUT the data will change.

{
  "matchedItems" :
  [
    { "itemID1" :
      { "Cost" : "12",
        "Size" : "small",
        "Colors" : [ "blue", "red" ]
      }
    },
    { "itemdID2" :
      { "Cost" : "33",
        "Size" : "large",
        "Colors" : [ "yellow" ]
      }
    }
  ]
}

so, I run thru the some things on the page and bundle up the data and return data sets, thus the hashes within the array.

BUT for the life of me, I can't get anything to look good in the actual .ajax post. When I console.log the data out, it looks good. Its an array of hashes. etc... looks fine. BUT the following is what is actually sent when I look at the params of the request. So below is what I am actually sending. It did some weird merging and such, it looks like.

{
  'matchedItems[0][itemid1][Color]' => 'Blue',
  'matchedItems[0][itemid1][Size]' => 'small',
  'matchedItems[0][itemid1][Cost]' => '33.90',
  'matchedItems[1][itemid2][Color][]' => ['Silver'],
  'matchedItems[1][itemid2][Size]' => 'small',
  'matchedItems[1][itemid2][Cost]' => '44',
  'matchedItems[2][itemid3][Color][]' => ['blue','Red'],
  'matchedItems[2][itemid3][Size]' => 'large',
  'matchedItems[2][itemid3][Cost]' => '23'
};

I tried to $.params the data, no luck. I tried various data settings in dataType, no luck. I am at a loss on how to format the data I send that mimics what I posted first.

Any ideas?

You should json_encode() your output from PHP

Example:

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

echo json_encode($arr);
?>

Output:

{"a":1,"b":2,"c":3,"d":4,"e":5}

You can use jQuery to decode the json you got back from the ajax reply:

var json_reply = jQuery.parseJSON('{"a":1,"b":2,"c":3,"d":4,"e":5}');
alert( json_reply.a ); // alerts "1"

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