简体   繁体   English

如何将“数组”值发送(放入)到XMLHttpRequest对象Ajax请求中?

[英]How to send (put) “Array” values into XMLHttpRequest Object Ajax Request?

We can send (put) single values to send into XMLHttpRequest with Ajax. 我们可以使用Ajax发送(put)单个值以发送到XMLHttpRequest。 But how to send "Array" element's values? 但是如何发送“数组”元素的值?

EXAMPLE#1 (Ok!) 示例#1(好的!)
For this simple value: 对于这个简单的值:

<input type="hidden" name="param" value="hello" />

We can simply put the value into XMLHttpRequest object like: 我们可以简单地将值放入XMLHttpRequest对象中,如:

xmlhttp.open("GET","ajax.php?param="+document.getElementById("param").value,true);
xmlhttp.send();

Above method is simple and ok. 上面的方法简单又可以。
But how about to send (put) "Array" values? 但是,如何发送(放置)“数组”值?

EXAMPLE#2 * (Problem with Array Values) Example#2 *(数组值问题)

<input type="hidden" name="param[]" value="hello" />
<input type="hidden" name="param[]" value="world" />
...
xmlhttp.open("GET","ajax.php?params="+document.getElementById("param").value,true);


Note: Server side will be with PHP. 注意:服务器端将使用PHP。

There is no difference (except for a slight change in name). 没有区别(除了名称略有变化)。 They are just elements with [] in the name attribute as far as HTML, JavaScript and HTTP are concerned. 就HTML属性,JavaScript和HTTP而言,它们只是名称属性中带有[]元素。 Only PHP is picky about naming conventions for form controls (every other server side language I've encountered deals with expectations of single or multiple values on the server alone, instead of both the server and the client) 只有PHP对表单控件的命名约定不挑剔(我遇到的所有其他服务器端语言都期望仅在服务器上而不是服务器和客户端上都具有单个或多个值)

The problem is that your initial approach isn't going to work (except in old IE and IE in quirks mode). 问题是你的初始方法不会起作用(除了旧的IE和IE在怪癖模式下)。 getElementById gets an element by its ID and your elements only have names. getElementById通过其ID获取元素,并且您的元素只有名称。

You can either give the elements IDs or use getElementsByName('param[]') and loop. 您可以给出元素ID或使用getElementsByName('param[]')和循环。

Note that you also need to use encodeURIComponent on the data to make it safe for sticking in a URL. 请注意,您还需要对数据使用encodeURIComponent ,以便可以安全地粘贴到URL中。

var inputs = document.getElementsByName('param[]');
var query = [];
for (var i = 0; i < inputs.length; i++) {
    var input = inputs[i];
    query.push( encodeURIComponent(input.name) + '=' + encodeURIComponent(input.value) );
}
var url = "ajax.php?" + query.join('&');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM