下面代码不管用,调式时控制台显示SyntaxError: unterminated regular expression literal,也看不懂,找了一上午也没找到原因
<!DOCTYPE html>
<html>
<head>
<title>json push还不管用</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js" type="text/javascript"></script>
<style>
ul {margin: 0; padding: 0;}
li { list-style: none;}
.txt { padding-left: 4px; outline: none;}
#ul{
color:red;
border:solid 1px blue;
}
</style>
</head>
<body>
<form action="#" method="get">
<label>
<input id="txt1" class="txt" type="text" name="UserName" placeholder="请输入姓名">
<input id="txt2" class="txt" type="text" name="Userscore" placeholder="请输入分数">
</label>
<input id="bsave" type="button" value="保存数据">
<input id="bshow" type="button" value="显示数据">
</form>
<ul id="myul">
<li id='xs'>下面是学生分数信息</li>
</ul>
<script>
var $name = $('#txt1');
var $score =$('#txt2') ;
var $txt = $('.txt');
//定义一个json对象,用于保存学生的相关资料
var myjson = "[{'name':'a','score':1},{'name':'b','score':2}]";
//push内容
var myarr = {
"name" : $name.val(),
"score" : $score.val()
};
$('#bsave').on('click', function () {
myjson.push(myarr);
$txt.val('');
});
$('#bshow').on('click',function () {
//通过$.each()工具函数,获取数组中各元素的名称与内容,显示在页面中。
$.each(myjson,function (index,obj) {
$('ul').append('<li>'+'姓名:'+obj.name+' 年龄:'+obj.socre</li>');
});
</script>
</body>
</html>麻烦大家帮忙看一下,谢了
首先你用的所有方法都是基于对象上封装的,push方法是数组特有,即意味这Array(这里必须是数组类型).push才能调用
JSON对象不是数组对象,在浏览器中的控制台可用这种方法验证(myjson instanceof Array || JSON instanceof Array),不是数组自然就没有数组的方法push,一般情况JSON数据由后端人员提供,JSON数据都是完整的,所以一般都不修改,修改的话也是后台直接更新JSON数据或接口,我列出几种容易混淆的格式吧
//关联数组其底层也是对象(key值为字符串)
var myarr = {
"name" : $name.val(),
"score" : $score.val()
};
//对象(key值比关联数组少了"")
var myObj ={
name:$name.val(),
score: $score.val()
}
//对象数组(每个key下面都是对象,该数组的key依然是普通的数字下标)
var myarr = [{name:'xiaoming'},{name:'xiaohong'}];
//JSON字符串对象(比关联数组多了"")---是字符转(typeof myjson可以验证;)
var myjson = "[{'name':'a','score':1},{'name':'b','score':2}]";
一般都说是关联数组转成JSON字符串,JSON.stringify("要转的关联数组");
来学习 留个脚印。
仅仅知道这些,见谅,如果有错误,还请立马通知我