简体   繁体   中英

HTML String and encoding

I think I'm chasing my tail a bit here and would appreciate someone setting me straight. In my Javascript program, I need to POST a HTML string using AJAX to my PHP server. The HTML string may have embedded image data in it.

Part 1: Simple case - HTML string is only text - for example - "Mmiz's question"

<p>Mmiz&#39;s question</p>

If I do nothing wrt encoding, the POST seems to clobber everything after the apostrophe and it's just "Mmiz" on the server side. Using escape() did not fix the problem either! What should I be doing to safely transport the html string to the server?

Part 2: If there is image data in the html, I base 64 URL safe encode the image data using:

encodeURIComponent(str).replace(/'/g,"%27").replace(/"/g,"%22");

Is this the right way to go about it?

Thanks for the guidance!

Mmiz

My guess is that you are sending your data either as GET data or form data. In either case, & marks the end of the parameter and that start of the next one. You MUST encode this. Additionally, it is a good idea to encode other characters too, such as using encodeURIComponent .

That said, you might want to look into an alternative method. For instance, I like to just submit my data straight to the server with no complications, so the request would look like:

POST /somefile.php HTTP/1.0
Host: example.com
Content-Type: text/plain     -- or some relevant type, like application/json
Content-Length: 13

Hello, World!

Then on the server side, in PHP in this case, I can just use file_get_contents("php://input") to retrieve the data, no problems whatsoever.

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