如何使用 jQuery“加载”来执行带有额外参数的 GET 请求?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1488593/
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 11:35:16  来源:igfitidea点击:

How can I use jQuery "load" to perform a GET request with extra parameters?

jqueryparametersloadhttp-get

提问by Thierry Lam

I'm reading the jQuery load documentationand it mentions that I can use load to perform a GET request by passing in extra parameters as a string. My current code with my parameters as key/value pair is:

我正在阅读jQuery load 文档,它提到我可以使用 load 通过将额外参数作为字符串传递来执行 GET 请求。我当前使用参数作为键/值对的代码是:

$("#output").load(
    "server_output.html",
    {
        year: 2009,
        country: "Canada"
    }
);

The above works fine but it's a post request. How can I modify the above to perform a GET request while still using load?

以上工作正常,但它是一个post请求。如何修改上述内容以在仍在使用的同时执行 GET 请求load

采纳答案by TJ L

According to the documentation you linked:

根据您链接的文档:

A GET request will be performed by default - but if you pass in any extra parameters in the form of an Object/Map (key/value pairs) then a POST will occur. Extra parameters passed as a string will still use a GET request.

默认情况下将执行 GET 请求 - 但如果您以对象/映射(键/值对)的形式传入任何额外的参数,则会发生 POST。作为字符串传递的额外参数仍将使用 GET 请求。

So the simple solution is to convert your object to a string before passing it to the function. Unfortunately, the documentation doesn't specify the format the string should be in, but I would guess it would be the same as if you were generating the GET request manually.

因此,简单的解决方案是在将对象传递给函数之前将其转换为字符串。不幸的是,文档没有指定字符串应该采用的格式,但我想这与您手动生成 GET 请求是一样的。

$("#output").load(
    "/server_output.html?year=2009&country=Canada"
);

回答by Kane

Use $.param(data):

使用$.param(data)

$("#output").load(
    "server_output.html?" + $.param({
        year: 2009,
        country: "Canada"})
);

回答by Scott Evernden

can you not just do:

你不能只做:

$("#output").load(
    "server_output.html?year=2009&country='Canada'"
);

回答by saturdayplace

$("#output").load("server_output.html?year=2009&country=Canada");

回答by Gua Syed

Use this

用这个

$("#output").load("server_output.html", {"2009":year, "Canada":country});