Home  >  Article  >  Backend Development  >  How to process JSON data returned by ajax in PHP

How to process JSON data returned by ajax in PHP

一个新手
一个新手Original
2017-10-09 09:22:061631browse

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="jquery-1.11.2.min.js"></script>
<title>无标题文档</title>
</head>
<body>
<select id="nation"></select>
</body>

<script type="text/javascript">
$.ajax({
    url:"jsonchuli.php",
    dataType:"JSON",
    success: function(data){
        var str ="";
            /*for(var i=0;i<data.length;i++)//关联数组里面的大小写和数据库里面的大小写是要保持一致的。
            {
                str = str+"<option value=&#39;"+data[i].Code+"&#39;>"+data[i].Name+"</option>";
            }
            $("#nation").html(str);*/
            
            for(var k in data)//这种方法相当于foreach方法遍历,上面注释的方法是for循环。
            {
                str = str+"<option value=&#39;"+data[k].Code+"&#39;>"+data[k].Name+"</option>";
            }
            $("#nation").html(str);
        }
    })

</script>

</html>
<?php
include("./DBDA.class.php");
$db = new DBDA();
$sql = "select * from nation";
//需要使用关联数组
//数组内容的编码格式必须是utf8的,其它的是不可以的。
echo json_encode($db->Query($sql,0));//返回的是关联数组。json_encode返回的是json数据。

 

The above is the detailed content of How to process JSON data returned by ajax in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn