客户端JSON解码jQuery

时间:2013-12-10 10:35:46

标签: php jquery json

请查看我的other question here

我正在尝试解决如何从PHP文件解码JSON响应。

JSON的结构如下:

[{
    "id": 1,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/amazon-webstore-379672",
        "price": " - "
    }
}, {
    "id": 2,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/we-need-someone-to-design-t-shirts-for-the-world-cup-2014-379671",
        "price": "\u00a3 50 "
    }
}, {
    "id": 3,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/unusual-request-for-expert-help-to-work-on-lowering-google-p-379670",
        "price": "\u00a3 50 "
    }
}, {
    "id": 4,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/1-to-2-developers-to-work-on-a-large-project-379669",
        "price": " - "
    }
}, {
    "id": 5,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/we-would-like-someone-to-design-some-world-cup-t-shirts-for-379665",
        "price": "\u00a3 50 "
    }
}, {
    "id": 6,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/graphic-design-of-3-x-sample-pages-for-a-website-379664",
        "price": "\u00a3 200 "
    }
}, {
    "id": 7,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/youtube-channel-art-379663",
        "price": "\u00a3 9 "
    }
}, {
    "id": 8,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/pr-events-organisation-source-prizes-for-charity-raffle-379661",
        "price": "\u00a3 100 "
    }
}, {
    "id": 9,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/wordpress-thesis-website-finessing-improve-main-opt-in-des-379659",
        "price": "\u00a3 40 "
    }
}, {
    "id": 10,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/i-would-like-my-logo-redesigned-updated-379651",
        "price": "\u00a3 10 "
    }
}, {
    "id": 11,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/pattern-maker-pattern-cutter-379650",
        "price": " - "
    }
}, {
    "id": 12,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/add-captcha-379652",
        "price": "\u00a3 30 "
    }
}, {
    "id": 13,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/setup-salesforce-api-so-we-can-just-pull-data-via-rest-379638",
        "price": "\u00a3 31 "
    }
}, {
    "id": 14,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/simple-map-illustration-379643",
        "price": "\u00a3 25 "
    }
}, {
    "id": 15,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/time-lapse-video-for-indoor-construction-project-12-week-p-379637",
        "price": "\u00a3 1.0k "
    }
}, {
    "id": 16,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/i-need-a-asterisk-vicidial-expert-to-help-support-us-379640",
        "price": "\u00a3 15 "
    }
}, {
    "id": 17,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/i-need-a-freelancer-to-provide-help-setting-up-cytoscape-379641",
        "price": "\u00a3 21 \/hr"
    }
}, {
    "id": 18,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/500-word-article-on-business-today-379632",
        "price": "\u00a3 12 "
    }
}, {
    "id": 19,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/web-interface-app-design-379629",
        "price": "\u00a3 20 \/hr"
    }
}, {
    "id": 20,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/distribute-leaflets-in-central-birmingham-379630",
        "price": "\u00a3 7 \/hr"
    }
}]

您可以在我的其他问题上查看当前的AJAX调用(此帖子顶部的链接)。

有没有人能够解释我如何解码JSON数组客户端?

我希望有这样的结构:

<div class="item">
    <div class="title">JSON Title</div>
    <div class="price">JSON Price</div>
</div>

3 个答案:

答案 0 :(得分:1)

这是你如何做到的。您需要的是JSON.parse()

<强> test.php的

<?php

// Ajax-Server Request Handler
if (isset($_GET['loadData'])) {
    exit(json_encode(array(
        array(
            'id' => 1,
            'info' => array('title' => 'http://www.peopleperhour.com/job/amazon-webstore-379672', 'price' => ' - ')
        ),
        array(
            'id' => 2,
            'info' => array('title' => 'http://www.peopleperhour.com/job/we-need-someone-to-design-t-shirts-for-the-world-cup-2014-379671', 'price' => '\u00a3 50 ')
        ),
        array(
            'id' => 3,
            'info' => array('title' => 'http://www.peopleperhour.com/job/unusual-request-for-expert-help-to-work-on-lowering-google-p-379670', 'price' => '\u00a3 50 ')
        )
    )));
}

?>

<!-- Ajax-Client -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">

// When Page Loads
$(document).ready(function()
{
    // Make Ajax Request
    $.get("test.php?loadData", function(data)
    {
        // Parse Data
        var jsonResults = JSON.parse(data);

        // Iterate Through Results
        $.each(jsonResults, function(key, value)
        {
            // Display Data
            $('.results').append(
                '<div class="item" id="'+ value.info.id +'">'+
                '<div class="title">'+ value.info.title +'</div>'+
                '<div class="price">'+ value.info.price +'</div>'+
                '</div>'
            );
        });
    });
});

</script>

<!-- HTML Page - Display Result -->
<div class="results"></div>

答案 1 :(得分:1)

注意:从您的其他问题来看,目前尚不清楚总是是否期望获得json答案,或者您是否可以接收json,html或xml。

如果你总是期待json:

$.ajax({ url: ..., data: ...,
    dataType: 'json', // <- tell jQuery to expect json,
                      // and to build a js object from the answer
    success : function(obj){
       //obj is a regular js object, built from the received json
       obj[i].info.title; // <- accessing this piece of data
    }
});

如果您的数据有时是json,有时则是其他内容:

success: function(data){
   var obj
   try {
       obj = JSON.parse(data);
       // if no exception is thrown, data was a valid json string,
       // and obj is a regular js object
       obj[i].info.title; // <- accessing this piece of data
   } catch (e) {
       // Maybe do something on error ?
   };
}

然后,您可以构建一个像hsuk建议的html字符串:

var html = '';
for(i=0; i < obj.length; i++) {
    html += '<div class="item">';
    html += '<div class="title">' + obj[i].info.title + '</div>';
    html += '<div class="price">' + obj[i].info.price + '</div>';
    html += '</div>';       
}
alert.html(html).fadeIn();

答案 2 :(得分:0)

实际上,关于JSON(JavaScript Object Notation)的有趣的一点是你可以在Javascript中使用它。

意思是,如果你的JSON字符串是{"foo": "bar"},你可以在Javascript中直接使用它:

var myObject = {"foo": "bar"};

var myJSONString = '{"foo": "bar"}';
var myObject = eval(myJSONString);

但也许您最好使用JSON.Parse,因为如果您正在解析用户数据,eval可能是漏洞,可能不一定是JSON格式。 (EG。通过HTTP发送的Json数据,客户端可能会混淆ti。)