美文网首页
js 数组对象想更换知识点

js 数组对象想更换知识点

作者: 云龙789 | 来源:发表于2019-03-18 11:28 被阅读0次
typeof(item) === 'undefined'
typeof(item) !== 'undefined' // 判断变量不存在

获取对象得长度

let item_arr= Object.keys(item); // 先获取对象中得所有键组成得数组
let item_len = item_arr.length  // 获取数组得长度

遍历对象

  $.each(object, function (key, val) {
     
                });

遍历数组

arr.forEach(function (item,key) {
                   
                });

对于 ajax 加载后,append 到某个 DOM 节点得 html 数据,如果想要做监听事件

比如 html  中 有 contentId=‘test’ 属性
     // 监听表单提交事件
        $('.submit_now').on('click', function () {
            let contentId = $(this).attr('contentId'); // 获取 contentId 属性得值
        })

必须使用 .on() 得语法

ES6 语法将 html 与js 结合


image.png

场景,将 ajax 请求得数据 append 到某个 DOM 节点上

1.es6 语法中有 `` 这个写法,可以将原本得 html 数组,直接放在  `` 符号中间。
2.变量可以使用 ${item} 得方式获取
3.如果有逻辑条件判断,可以再外层先定义一个数组 arr =[],然后再循环内,将符合条件得数据复制给一个 html 变量,
  在循环节后后,将 html 得数据 push 到 arr 数组中,整个遍历结束后,将 arr 追加到节点上

如果一个对象需要作为参数传递,需要先转换成字符串再传递。如果是需要传递给后端得话,还需要使用 encodeURIComponent()
进行编码。这个函数相当于php 得 urlencode。这个函数能够处理特殊符号,保证请求数据不会出现错误。

<script>
obj = {
    "name":"test"
}
 let str = (encodeURIComponent(JSON.stringify(obj)))
console.log((str))
console.log(decodeURIComponent(str))

    let string = JSON.stringify(obj);
console.log(string)
    console.log(JSON.parse(string))
</script>
image.png

前后端交互

<script>
    obj = {
        "name": "test"
    }
    let str = (encodeURIComponent(JSON.stringify(obj)))
    $(function () {
        $.ajax({
            type: 'GET',
            url: 'http://test/client.php',
            data: {
                "obj":str
            },
            dataType: 'json',
            success: function (res) {
                console.log(res)
            }
        })
    })

</script>
后端
<?php
echo urldecode($_GET['obj']);
image.png

相关文章

网友评论

      本文标题:js 数组对象想更换知识点

      本文链接:https://www.haomeiwen.com/subject/ulcvmqtx.html