简体   繁体   English

使用带有主体和URL参数的JQuery的AJAX POST请求

[英]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. 我正在学习如何使用JQuery进行AJAX调用,我想知道是否有可能做的一件事是在帖子正文中包含一些URL参数数据和其他数据。 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. 但是除了要在POST请求正文中发送的JSON数据外,我还要添加URL参数。 Is there a way to do this? 有没有办法做到这一点?

You would be able to include the variables in the url portion of your code. 您可以将变量包含在代码的url部分中。 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. 您可能需要在example1变量两边加上引号,以确保当URL中有空格时它不会中断。

You can send parameters normally in the URL as in the get request either using ? 您可以像使用get请求一样,在URL中正常发送参数,或者使用? 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. 在URL上包含参数的方式将取决于您在服务器端接收/解析参数的方式,但是对于发布请求,这不被认为是一种好习惯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM