简体   繁体   English

在Javascript中使用AJAX提交2D数组表单输入

[英]Submitting 2D array form input using AJAX in Javascript

I have a form as follows: 我的表格如下:

<form name="chat" id="chat" action="" onsubmit="sendMessage()">
 <a name="chat">&nbsp;</a>
 <input type="text" name="chat" id="chat" size="38" maxlength="50" vertical-align="middle">
 <input type="hidden" name="action" id="action" value="checkresponse">
 <input type="hidden" name="response_Array[sessionid]" id="response_Array[sessionid]" value="keu88lh88ini89dgnccob54f27"><br>
 <input type="text" name="response_Array[top]" id="response_Array[top]" value="a">
 <input type="text" name="response_Array[second]" id="response_Array[second]" value="b"><br>
 <input type="text" name="response_Array[third]" id="response_Array[third]" value="c"><br>
 <input type="text" name="response_Array[fourth]" id="response_Array[fourth]" value="d"><br>
 <input type="text" name="response_Array[input][0]" id="response_Array[input][0]" value="input 0"><br>
 <input type="text" name="response_Array[that][0]" id="response_Array[that][0]" value="that 0"><br>
 <input type="submit" name="submit" id ="submit" value="SEND" style="width: 45px">
 </form>

When the user clicks Submit, I need to send all the input fields to the server. 当用户单击“提交”时,我需要将所有输入字段发送到服务器。 But, the page should not get refreshed. 但是,该页面不应刷新。 So, I have created sendMessage(),in which I have used XMLHttpRequest object to send the form submit request. 因此,我创建了sendMessage(),其中使用XMLHttpRequest对象发送表单提交请求。

To read input fields, I have used in sendMessage(): 为了读取输入字段,我在sendMessage()中使用了:

var infoStr = "chat="+document.forms[0]['chat'].value;
infoStr += "&action="+document.forms[0]['action'].value;

I want to know how should I read the 2D array :response_Array and parse it into a JSON string so that it can be passed to the php server code. 我想知道如何读取2D数组:response_Array并将其解析为JSON字符串,以便可以将其传递给php服务器代码。

It is so simple 很简单

var infoStr=""
for(var i=0;i<document.forms[0].elements.length;i++)
{
   infoStr+=document.forms[0].elements[i].name+"="+document.forms[0].elements[i].value+"&";
}

alert(infoStr); // You will have the full name value pairs.

Hope this solves your problem. 希望这能解决您的问题。

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

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