使用jquery进行POST,如何正确提供“数据"参数? [英] Using jquery to make a POST, how to properly supply 'data' parameter?

查看:67
本文介绍了使用jquery进行POST,如何正确提供“数据"参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以POST方式进行ajax调用,它将转到我的servlet.我想发送参数化的数据,如下所示:

I'd like to make an ajax call as a POST, it's going to go to my servlet. I want to send parameterized data, like the following:

var mydata = 'param0=some_text&param1=some_more_text';

我将其作为我的jquery ajax()调用的数据"参数提供.因此,应该将其插入POST正文中,对吗? (我是说,没有附加到我的"mysite/save"网址中?):

I supply this as the 'data' parameter of my jquery ajax() call. So this should be inserted in the body of the POST, right? (I mean, not appended to my 'mysite/save' url?):

$.ajax({
    url: 'mysite/save',
    type: 'POST',
    data: mydata
});

它似乎正常工作.在我的servlet中,我只是转储了所有接收到的参数,并且看到它们都很好地通过了:

it appears to work correctly. In my servlet, I am just dumping all received parameters, and I see them all come through nicely:

private void printParams(HttpServletRequest req) {
    Enumeration paramNames = req.getParameterNames();
    while (paramNames.hasMoreElements()) { 
        // print each param key/val here.
    }
}

另外,我应该在使用之前手动对数据字符串进行url编码,对吗?喜欢:

also, I should url encode my data string manually before use, right? Like:

var mydata = 'param0=' + urlencode('hi there!');
mydata += '&param1=' + urlencode('blah blah');
mydata += '%param2=' + urlencode('we get it');

谢谢!

推荐答案

一种更简单的方法是将data属性作为对象提供,如下所示:

An easier way is to provide the data property as an object, like this:

$.ajax({
  url: 'mysite/save',
  type: 'POST',
  data: { param0:'hi there!', param1:'blah blah', param2:'we get it' }
});

否则,是的,您应该对其进行编码,例如,任何带有&的东西都会很快弄乱.无论如何,以我的观点,将其作为对象提供是一种更为轻松/简单的方法.

Otherwise, yes you should encode it, as anything with an & for example would screw things up very quickly. Providing it as an object is a much cleaer/simpler approach though, in my opinion anyway.

您也可以将其隔开,并从其他内联位置检索属性,如下所示:

You can also space it out, and retrieve properties from other places inline, like this:

$.ajax({
  url: 'mysite/save',
  type: 'POST',
  data: { 
          param0: $('#textbox0').val(), 
          param1: $('#textbox1').val(), 
          param2: $('#textbox2').val()
        }
});

如果您想知道jQuery如何在内部进行此编码,请使用此处.

If you're curious how jQuery does this encoding internally, it's using $.param() (which you can use directly as well) to encode the object to a string, called here, and the guts here.

这篇关于使用jquery进行POST,如何正确提供“数据"参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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