jQuery 将查询字符串添加到 Ajax url 调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10544895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:29:51  来源:igfitidea点击:

Adding query string to Ajax url call

jqueryajaxurl

提问by H.dev.guy

I wanna kn is it possible to pass query string along with URL when we call on Jquery Ajax;

我想知道当我们调用 Jquery Ajax 时,是否可以将查询字符串与 URL 一起传递;

Example :

例子 :

    $.ajax({
           type: "POST",
           url: "index.php?task=addNewInfo",
           data: $('#regForm').serialize(),
           dataType: "json",
              .....
      });  

So does the query string from the param task works fine? or we need to do it the other way? Thank you.

那么来自 param 任务的查询字符串工作正常吗?或者我们需要以另一种方式来做?谢谢你。

回答by Imdad

Send the task in the data parameter

发送数据参数中的任务

data:"task=addNewInfo&" + $('#regForm').serialize()

This is for using POST method. If you want to use GET method then Arun's solution will work fine.

这是用于使用 POST 方法。如果您想使用 GET 方法,那么 Arun 的解决方案将可以正常工作。

回答by Arun P Johny

I think the following will work fine

我认为以下将正常工作

url : "index.php?task=addNewInfo&" + $('#regForm').serialize()

But why do you want to pass the form values as query params? The post request will pass the values as request params anyway. These params will be sent via the request body which is why you are using POSTrequest type.

但是为什么要将表单值作为查询参数传递呢?无论如何,发布请求都会将值作为请求参数传递。这些参数将通过请求正文发送,这就是您使用POST请求类型的原因。

回答by Arun P Johny

Yes. query-string and request body are 2 different things in HTTP requests. jQuery wrap the data in the query-string for GET requests, which is probably the source of confusion

是的。查询字符串和请求正文是 HTTP 请求中的两种不同的东西。jQuery 将数据包装在 GET 请求的查询字符串中,这可能是混淆的根源

  • GET request: the body (or payload) is empty, only the url holds data.
  • POST request: fill the body as you like, either with url-encoding like you did, or with json-encoding
  • GET 请求:正文(或有效负载)为空,只有 url 保存数据。
  • POST 请求:根据需要填充正文,可以像您一样使用 url-encoding,或者使用 json-encoding