简体   繁体   中英

convert json object to serialized string for server side processing?

I'm trying to convert a returned json object into a serialized string that I can process further with some PHP server side code:

The returned object looks like this:

Object {id: "123456787654321", email: "some-email@gmail.com", first_name:   "First", gender: "male", last_name: "Last"}

I can convert the object to a string with the following:

var paramString = JSON.stringify(response);
console.log(paramString);

// doesn't work
//var params = paramString.serialize();

How do I now convert the string to a serialized string that I can pass to my server with the following client side call:

I would expect something like this:

id=123456787654321&email=some-email@gmail.com&first_name...

My server side code:

$.post("/functions/test_functions.php", {params: params}, function(data) {
    ...                             
}, "json");

I handle the params array like this server side:

$vars = $_SERVER['REQUEST_METHOD'] === "GET" ? $_GET : $_POST; 

$params = array();
isset($vars['params']) ? parse_str($vars['params'], $params) : null;

You can pass JSON-string to server and decode it with json_decode(). See http://php.net/manual/en/function.json-decode.php for details.

Unless there's a specific reason for stringifying, you don't actually need to. jQuery .post will handle the serialization for you, for example:

var response = {id: "123456787654321", email: "some-email@gmail.com", first_name:   "First", gender: "male", last_name: "Last"};
$.post("/functions/test_functions.php", response, function(data) {
    ...                             
}, "json");

Will make a POST request like this:

/functions/test_functions.php
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Form Data: id=12345654321&email=some-email@gmail.com&first_name....

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