0

I am using $.ajax() to make a web service call from my client script. The data for this call is defined as follows.

data: "{ term: '" + request.term + "' }",

The problem is that request.term contains what the user typed into a text box. So what happens if it contains quotes or other unexpected characters?

Is there a function to escape any such characters so that the resulting JSON string will be correctly formed?

1 Answer 1

2

Don't build JSON by hand.

Don't manually escape data for JSON.

Use JSON.stringify.

var obj = {
    term: request.term
};
var json = JSON.stringify(obj);
// etc
data: json,
Sign up to request clarification or add additional context in comments.

6 Comments

Even if I follow this advice, my actual code contains additional text that must be combined with the text entered by the user. How can I form such a string without invalid characters?
@JonathanWood — That's what JSON.stringify does.
@JonathanWood — If, by "multiple data items", you mean "objects with more than one property" then it works in the same way as an object with a single property. A JavaScript data structure goes in and a string of JSON comes out.
Thanks, but I'm still missing something. If my string would've been term: ' + request.term + ', arg2: ' + blah2 + ', arg3: ' + blah3. How do I safely pass that to JSON.stringify() or anything else.
You don't build the JSON string by hand.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.