简体   繁体   中英

AJAX POST request using JQuery with body and URL parameters

I'm learning how to make AJAX calls with JQuery and one thing I was wondering if it's possible to do is include some data as URL parameters and other data in the post body. For example, I'd like to do something like this:

$.ajax({
  url: '/myURL',
  type: 'POST',
  data: JSON.stringify(data),
  contentType: 'application/json; charset=utf-8'
})

but in addition to the JSON data which is being sent in the POST request body, I'd like to include URL parameters. Is there a way to do this?

You would be able to include the variables in the url portion of your code. For example

var example1 = "some_information";

$.ajax({
  url: '/myURL',
  type: 'POST',
  data: JSON.stringify(data),
  contentType: 'application/json; charset=utf-8'
})

would become

var example1 = "some_information";

$.ajax({
  url: '/myURL?var1=example1',
  type: 'POST',
  data: JSON.stringify(data),
  contentType: 'application/json; charset=utf-8'
})

You may need to put quotes around the example1 variable to ensure it doesn't break when there are spaces in the url.

You can send parameters normally in the URL as in the get request either using ? and &

$.ajax({
  url: '/myURL?data2=' + data2 + '&data3=' + data3,
  type: 'POST',
  data: JSON.stringify(data),
  contentType: 'application/json; charset=utf-8'
})

or by set them between /

$.ajax({
 url: '/myURL/' + data2 + '/' + data3,
 type: 'POST',
 data: JSON.stringify(data),
 contentType: 'application/json; charset=utf-8'
})

The way of including the parameters on the URL will depends of the way you receive/parse them on the server side, however this is not considered as good practice for the post request.

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