試圖學習json由於工作需要...我試圖添加和刪除記錄到json對象動態...可以有人告訴我爲什麼我不斷收到UNDEFINED消息....這裏是代碼..感謝您的幫助!Json in Javascript
<html>
<head>
<title>TEST</title>
<script language="Javascript" type="text/javascript">
function addC(){
var index = document.getElementById('type').selectedIndex;
var type = document.getElementById('type').options[index].value;
var name = document.getElementById('inpName').value;
var date = document.getElementById('inpDate').value;
processJson(type,name,date);
return false;
}
function processJson(type,name,date){
var count = document.getElementById('counter').value*1;
var currentRecords = document.getElementById('holder').value;
var newRecordType = "{\"name\":\""+type+"\",";
var newRecordName = "\"type\":\""+name+"\",";
var newRecordDate = "\"date\":\""+date+"\"}";
var newRecord = newRecordType + newRecordName + newRecordDate;
if(count > 0){
newRecord = "," + newRecord;
}
var updatedRecord = currentRecords + newRecord;
var jsonObj = {"allrows" : "["+updatedRecord+"]"};
document.getElementById('counter').value=(document.getElementById('counter').value *1)+ 1;
document.getElementById('holder').value=updatedRecord;
}
function deleteRow(){
var toDel = document.getElementById('inpDel').value;
alert(toDel);
var current = "[" + document.getElementById('holder').value + "]";
alert(current);
var jsonO = {"allRows" : current};
alert(jsonO);
var t = jsonO.allRows[toDel].type;
alert("Deleting - " + t);
return false;
}
</script>
</head>
<body>
<form name="frm" action="">
<table>
<tr>
<td>
<select name="type" id="type">
<option value="creator">Creator</option>
<option value="editor">Editor</option>
<option value="publisher">Publisher</option>
</select>
</td>
<td>
<input type="text" name="inpName" id="inpName" value="">
</td>
<td>
<input type="text" name="inpDate" id="inpDate" value="">
</td>
<td>
<input type="text" name="inpDel" id="inpDel" value="">
</td>
<td>
<input type="button" name="cmdAdd" value="Add" onClick="return addC();">
<input type="button" name="cmdAdd" value="Del" onClick="return deleteRow();">
</td>
</tr>
<tr>
<td><input type="text" name="counter" id="counter" value="0">
</tr>
<tr>
<td colspan="3">
<textarea name="holder" id="holder" rows="20" cols="60"></textarea>
</td>
</tr>
</form>
</body>
</html>
你操縱JSON(串)。餿主意。只需使用實際的JavaScript對象。 – MvanGeest 2010-07-29 09:51:22
雖然可能不是。你究竟想要做什麼?你需要什麼JSON? – MvanGeest 2010-07-29 09:56:34
無論如何,在http://jsfiddle.net/jdGWM/上創建了一個jsFiddle。 'window.addC'只是一個解決方法。 – MvanGeest 2010-07-29 09:57:16