开发者

What's the correct way to get HTML from an AJAX Response in JSON Format?

I have an AJAX request that creates a 'post', and upon successful post, I want to get HTML to inject back into the DOM. Right now I'm returning a JSON array that details success/error, and when I have a success I also include the HTML for the post in the response. So, I parse the response as JSON, and set a key in the JSON array to a bunch of HTML Code.

Naturally, the HTML code is making the JSON array break -- wha开发者_StackOverflow中文版t should I do to escape it (or is there a better way to do this?). I get an AJAX response with a JSON array like so:

[{response:"success"},{html:'<div class="this is going to break...

Thanks!


Contrary to what you're probably used to in JavaScript, ' can't begin a string in JSON. It's strictly a ". Single quotes work when you're passing JSON to JavaScript.. much like <br> works when you want to put an XHTML line break.

So, use " to open the HTML string, and sanitize your quotes with \".

json.org has more info WRT what you should sanitize. Though the list of special characters isn't long, it's probably best to use a library like Anurag suggests in a comment.


Apart from escaping double quotes as mention by BranTheMan, newlines also break JSON strings. You need to replace newlines with \n.

Personally I've found this to be enough:

// Don't know what your serverside language is, example in javascript syntax:

print(encodeJSON({
    response : "success",
    html : htmlString.replace(/\n/g,'\\n').replace(/"/g,'\\"')
}));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜