jquery 处理json字符串

      jquery的ajax方法可以从后台传回json数据,但怎么样将json数据转换成json对象呢,查过手册后看到了jquery的工具函数$.parseJSON().下面个小例子

前台页面代码:  

  <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="jquery.js">

</script>
<script>
           function tj() {
                $.ajax({
                type : 'post',
                url : 'Process.php',
                data : $("form").serialize(),
                datatype :'json',
                success : function(msg) {
                console.info(msg);
                obj=$.parseJSON(msg);
               $('p').html(obj.username);
      
                    }
            });
         }
</script>
</head>
<body>
        <form id="login" method="post"  onsubmit="tj(); return false;">
            <input type="text" name="username" /><br/>
            <input type="password" name="pwd" /> 

            <input  type="submit"  />

        </form>
       <p></p>
</body>
</html>

后台php代码:

          <?php
                echo json_encode($_POST);
            ?>

jquery得到后台返回去的json字符串,然后利用$.parseJSON()将返回的数据解析成json对象,我们便可以用对象.属性的方法取得数据了。

你可能感兴趣的:(jquery 处理json字符串)