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

Submitting 2D array form input using AJAX in Javascript

本文关键字:数组 表单 输入 2D 提交 Javascript 中的 AJAX 使用      更新时间:2023-09-26

我有一个如下形式:

<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>

当用户单击Submit时,我需要将所有输入字段发送到服务器。但是,页面不应该刷新。因此,我创建了sendMessage(),在其中我使用XMLHttpRequest对象发送表单提交请求。

为了读取输入字段,我在sendMessage()中使用了:

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

我想知道我应该如何读取2D数组:response_array并将其解析为JSON字符串,以便将其传递给php服务器代码。

它是如此简单的

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.

希望这能解决你的问题。