Home >Web Front-end >Front-end Q&A >How to use $.param method without URL encoding
When using jQuery's Ajax request, we often use the $.param method to serialize an object into a query string to facilitate data transmission. The $.param method automatically URL-encodes the data, for example, converting spaces to . However, sometimes we want to serialize the object without URL encoding and keep it as it is. This article will introduce how to use the $.param method without URL encoding.
First, let’s take a look at the basic usage of the $.param method. Suppose there is the following object:
var data = { name: 'John Doe', age: 30, company: 'ABC Inc.', address: { street: '123 Main St', city: 'Anytown', state: 'CA', zip: '12345' } };
We can use the $.param method to serialize it into a query string, as shown below:
var queryString = $.param(data); // queryString 的值为: // "name=John%20Doe&age=30&company=ABC%20Inc.&address%5Bstreet%5D=123%20Main%20St&address%5Bcity%5D=Anytown&address%5Bstate%5D=CA&address%5Bzip%5D=12345"
As you can see, the $.param method serializes the object The URL is encoded, spaces are converted to , and some special characters are encoded. If we want to keep the original look, we need to use a little trick.
First, we need to define a function that does not perform URL encoding, as follows:
function serializeParam(obj) { var str = []; for (var p in obj) { if (obj.hasOwnProperty(p)) { str.push(encodeURIComponent(p) + '=' + obj[p]); } } return str.join('&'); }
The function of this function is to convert the object into a string, which does not perform URL encoding. Next, we can use this function to serialize the object into a query string, as shown below:
var queryString = Object.keys(data).map(function(key) { var value = data[key]; if (typeof value === 'object') { value = serializeParam(value).replace(/%20/g, '+'); } return encodeURIComponent(key) + '=' + value; }).join('&'); // queryString 的值为: // "name=John Doe&age=30&company=ABC Inc.&address[street]=123 Main St&address[city]=Anytown&address[state]=CA&address[zip]=12345"
As you can see, the query string generated by this method is not URL-encoded, but spaces are replaced. Became a plus. Therefore, if the server receiving the data can support this method of transmission, we can use this method.
In conclusion, by using a custom function, we can serialize objects in jQuery without URL encoding to meet our special needs.
The above is the detailed content of How to use $.param method without URL encoding. For more information, please follow other related articles on the PHP Chinese website!