如何从jQuery的$ .get方法中提取对象?

时间:2011-04-13 23:46:03

标签: javascript jquery json object callback

我正在尝试使用jQuery的$ .get方法从回调中返回单个对象。

我可以轻松显示整个回调,但无法从方法中选择单个对象

这是我的代码:

<script>
    $.get("http://domain.com/marketplace/api/v0/random_business_json/?callback=mycallback",
    function(data){
        $('.result').html(data);
    });
</script>

以下是我的浏览器中返回的回调:

mycallback([{"pk": 6484, "model": "business.business", "fields": {"point": "POINT (-122.5447999999999951 45.7806700000000006)", "fax": "360-687-3148", "validated": true, "meta_description": null, "city": "Battle Ground", "mailing_zip_code": null, "mailing_address2": null, "state": "WA", "mailing_address1": null, "extension2": null, "extension1": null, "hours_text": "Opens Thursday\n at 8:30 a.m.", "latitude": "45.780670", "thumbnail": null, "zip_code": "98604", "website": "", "suggested_type": "", "description": "", "phone2": "", "address1": "713 West Main Street", "address2": "Suite 101", "phone1": "687-3149", "default_hours": null, "nickname": "", "slug": "boyd-james-m", "categories": [1218, 1227], "additional_hours_info": "", "business_type": 6, "name": "Boyd, Gaffney, Sowards, Mc Cray, Treosti, PLLC", "created": "2010-05-12 22:52:38", "safe_description": "", "notes": "Owner: STEVEN SOWARDS\n\nCONTACT_NAME: STEVEN SOWARDS\nTITLE_DESC: \n", "pre_name": "", "modified": "2010-05-12 22:52:48", "longitude": "-122.544800", "email": "", "mailing_state": null, "mailing_city": null}}])

我希望能够像pk,fields,ct等一样拉出来......

我尝试用 $('。result')。html(data.pk); 替换 $('。result')。html(data); 看看这样的东西是否有用但没有成功。

任何帮助都将不胜感激。

谢谢!

3 个答案:

答案 0 :(得分:2)

如果响应是JSON,则成功回调data参数是对象。试图将其解析为HTML没有意义:

function(data) {
    alert("pk = " + data[0].pk);
}

答案 1 :(得分:0)

尝试$('.result').html(data[0].pk);

答案 2 :(得分:0)

jQuery.getJSON()有JSONP支持。这可能就是你要找的东西。

在网址中使用?callback=?代替?callback=mycallback,以使其正常运行。

http://api.jquery.com/jQuery.getJSON/