简体   繁体   中英

Safest way to send JSON string to PHP server

I've been trying to send a JSON string to PHP server like this:

$.ajax({  
    type: "POST",  
    url: "themes.php?page=themeoptions",  
    data: {structure : JSON.stringify(structure)},    
});

However, every quotation mark from the string I send is escaped automatically, so I can't decode it in PHP with json_decode(). I could remove all the escape characters, but I really doubt that this way of sending JSON data to server is safe.

So, I was wondering if you have any ideas on how to do that in a simple and safe (not necessarily bulletfroof) way?

Thank you!

You can just do '{"structure":' + JSON.stringify(structure) + '}' or {structure: structure}

The first one is a JSON String so jQuery doesn't need to parse it. The second is a javascript object, so jQuery knows exactly how to parse it.

But you are mixing the two, so jQuery is confused and re-encodes your object, because you encoded only half your object.

So another alternative would be JSON.stringify({structure: structure })

Try this

$.ajax({  
    type: "POST",  
    url: "themes.php?page=themeoptions",  
    data: {structure: structure},    
});
$.ajax({  
    type: "POST",  
    url: "themes.php?page=themeoptions",  
    data: structure,    
});

Quoting from the documentation :

dataObject String

Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).

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