How do you pass multiple parameters of the same type to jQuery Get

你说的曾经没有我的故事 提交于 2019-12-19 05:34:42

问题


I'm trying to GET some data from a site using jQuery $.get. I need to set 2 parameters of the same type:

..&q=Some Text&q=Some other text

jQuery appears to be overwriting the first instance of q with the second and only sending 1. Any way around this?

This is the code I was trying to use:

var params = {
       "otherParam":"x",
       "q":text,
       "q":title
};
$.get(url, params, mySuccessFunction);

回答1:


Try:

var params = {
  "otherParam": "x",
  "q": [ text, title ]
};

edit — more information: array-valued parameters like that are treated specially by jQuery. To appease many common server frameworks, by default (since release 1.5 or 1.6 I think) those will result in parameter names that include "[]" (open- and close-bracket characters) as a suffix (no number, contrary to my erroneous comment below). If you don't want that, you can set

jQuery.ajaxSettings.traditional = true;

and it'll just be "q" instead of "q[]".




回答2:


And another way to solve it that does not require encodeURIComponent() or messing with jQuery.ajaxSettings.traditional = true; which I would prefer not to do because I don't want to interfere (even temporarily) with what other parts of the site might be doing simultaneously.

Is:

 var params=[ 
       {name:"q", value:title},
       {name:"q", value:text}
 ];
 $.get(url, params, mySuccessFunction);



回答3:


Another approach without modifying jQuery.ajaxSettings.traditional = true; is to use $.param() http://api.jquery.com/jQuery.param/

So something like this:

var params = {
  "otherParam": "x",
  "q": [ text, title ]
};

$.get(url, $.param(params, true), mySuccessFunction);



回答4:


You can write the URL like this :

$.get(
   url+'?q='+encodeURIComponent(text)+'&q='+encodeURIComponent(title)+'&otherParam='+encodeURIComponent('x'),
   mySuccessFunction
);



回答5:


Things are pretty simple and described in jQuery website http://api.jquery.com/jquery.param/.

First create a params object

var params=[{
    name: 'param1',
    value: 'hello'
},
{
    name: 'param1',
    value: 'alex'
}];

next create the data to be sent to the service.

var data = jQuery.param(params);

That object can be inserted as the data param of the ajax request. I like using a settings object

var settings={
    url: 'api/domain/timeline',
    type: 'get',
    contentType: 'application/json',
    data: data
    };
$.ajax(settings);


来源:https://stackoverflow.com/questions/12876373/how-do-you-pass-multiple-parameters-of-the-same-type-to-jquery-get

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!