如何在Ajax调用中获取JSON数据 [英] How to get JSON data on ajax call

查看:405
本文介绍了如何在Ajax调用中获取JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过ajax调用从php页面获取JSON数据.php页面正在返回AJAX字符串,现在我必须获取该JSON数据并分别显示值.

i am trying to get the JSON data from php page on ajax call.The php page is returning the AJAXstring, now i have to get that JSON data and display values separately.

我该怎么做?

这是我正在使用的代码.... 当我运行此代码以获取数据product_id时,它显示警报未定义.

here is code i am using.... When i run this code to get the data product_id, it is showing alert undefined.

代码:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Request json test</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script language="JavaScript">
$(document).ready(function(){
    $("#testjson").click(function(e){
        startJsonSession();
        return false;
    });

    function startJsonSession(){  
        $.ajax({
            url: "index.php",
            cache: false,
            dataType: "json",
            complete: function(data) {
                pid = data.product_id;
                alert(pid);
            }
        });
    }
}); 
</script>

</head>
<body>
<a href="#" id="testjson">Get JSON Data</a>
<div id="showdata"></div>
</body>
</html>

index.php的JSON输出:

JSON output from index.php:

[{"ID":"1","product_id":"3","image_name":"cycle5.png","image_type":".jpg"},{"ID":"2","product_id":"6","image_name":"cycle3.png","image_type":".jpg"},{"ID":"3","product_id":"4","image_name":"cycle2.png","image_type":".jpg"},{"ID":"4","product_id":"43","image_name":"cycle1.png","image_type":".jpg"},{"ID":"5","product_id":"7","image_name":"cycle8.png","image_type":".jpg"},{"ID":"6","product_id":"9","image_name":"cycle0.png","image_type":".jpg"},{"ID":"7","product_id":"543","image_name":"cycle6.png","image_type":".jpg"},{"ID":"8","product_id":"445","image_name":"cycle9.png","image_type":".jpg"},{"ID":"9","product_id":"453","image_name":"cycle75.png","image_type":".jpg"},{"ID":"10","product_id":"725","image_name":"cycle86.png","image_type":".jpg"}]

推荐答案

首先获得product_id

pid = data[0].product_id
alert(pid);

小提琴演示

要从响应中获取每个product_id

complete: function(data) {
    $.each(data,function(){
        alert(this.product_id);
    });
}

小提琴演示

这篇关于如何在Ajax调用中获取JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆