To add query parameters to a url using jQuery AJAX, you do this:
要使用jQuery AJAX向url添加查詢參數,可以這樣做:
$.ajax({
url: 'www.some.url',
method: 'GET',
data: {
param1: 'val1'
}
)}
Which results in a url like www.some.url?param1=val1
哪個url會產生如www.some.url?param1=val1
How do I do the same when the method is POST? When that is the case, data no longer gets appended as query parameters - it instead makes up the body of the request.
當方法是POST時,我該怎么做呢?在這種情況下,數據不再作為查詢參數添加,而是作為請求的主體。
I know that I could manually append the params to the url manually before the ajax request, but I just have this nagging feeling that I'm missing some obvious way to do this that is shorter than the ~5 lines I'll need to execute before the ajax call.
我知道我可以在ajax請求之前手動將解析器附加到url,但我有一種揮之不去的感覺,我錯過了一些明顯的方法,這些方法比ajax調用之前需要執行的大約5行要短。
1 个解决方案
#1
7
jQuery.param() allows you to serialize the properties of an object as a query string, which you could append to the URL yourself:
param()允許您將對象的屬性序列化為查詢字符串,您可以將其附加到URL中:
$.ajax({
url: 'http://www.example.com?' + $.param({ paramInQuery: 1 }),
method: 'POST',
data: {
paramInBody: 2
}
});