【问题标题】:Submitting 2D array form input using AJAX in Javascript在 Javascript 中使用 AJAX 提交二维数组表单输入
【发布时间】:2012-01-11 13:26:17
【问题描述】:

我的表格如下:

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

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

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

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

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

【问题讨论】:

  • 为什么不直接使用 jQuery 及其.json 方法?

标签: javascript ajax arrays


【解决方案1】:

就是这么简单

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.

希望这能解决您的问题。

【讨论】:

    猜你喜欢
    • 2013-01-06
    • 1970-01-01
    • 1970-01-01
    • 2013-05-19
    • 1970-01-01
    • 1970-01-01
    • 2013-07-01
    • 2012-12-03
    • 1970-01-01
    相关资源
    最近更新 更多