将多个参数传递给 jQuery ajax 调用 [英] Pass Multiple Parameters to jQuery ajax call

查看:32
本文介绍了将多个参数传递给 jQuery ajax 调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 jquery 代码在 aspx 页面中调用 webmethod

I have the following jquery code to call a webmethod in an aspx page

$.ajax({
    type: "POST",
    url: "popup.aspx/GetJewellerAssets",
    contentType: "application/json; charset=utf-8",
    data: '{"jewellerId":' + filter + '}',
    dataType: "json",
    success: AjaxSucceeded,
    error: AjaxFailed
});

这里是网络方法签名

[WebMethod]
public static string GetJewellerAssets(int jewellerId)
{

这很好用.

但是现在我需要将两个参数传递给 web 方法

But now I need to get two parameters passed to the web method

新的网络方法看起来像这样

the new web method looks like this

[WebMethod]
public static string GetJewellerAssets(int jewellerId, string locale)
{
}

如何更改客户端代码以成功调用此新方法签名?

How do I change the client code to successfully call this new method signature ?

以下两种语法有效

data: '{ "jewellerId":' + filter + ', "locale":"en" }',

data: JSON.stringify({ jewellerId: filter, locale: locale }),

其中 filter 和 locale 是局部变量

where filter and locale are local variables

推荐答案

不要使用字符串连接来传递参数,只使用数据哈希:

Don't use string concatenation to pass parameters, just use a data hash:

$.ajax({
    type: 'POST',
    url: 'popup.aspx/GetJewellerAssets',
    contentType: 'application/json; charset=utf-8',
    data: { jewellerId: filter, locale: 'en-US' },
    dataType: 'json',
    success: AjaxSucceeded,
    error: AjaxFailed
});

<小时>

更新:

正如@Alex 在评论部分所建议的,ASP.NET PageMethod 期望参数在请求中是 JSON 编码的,因此 JSON.stringify 应该应用于数据哈希:

As suggested by @Alex in the comments section, an ASP.NET PageMethod expects parameters to be JSON encoded in the request, so JSON.stringify should be applied on the data hash:

$.ajax({
    type: 'POST',
    url: 'popup.aspx/GetJewellerAssets',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({ jewellerId: filter, locale: 'en-US' }),
    dataType: 'json',
    success: AjaxSucceeded,
    error: AjaxFailed
});

这篇关于将多个参数传递给 jQuery ajax 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆