How to extract objects from jQuery's $.get method?
I am trying to return individual objects from a callback using jQuery's $.get method.
I can easily display the whole callback but can't pick individual objects from the method
Here's my code:
<script>
$.get("http://domain.com/marketplace/api/v0/random_business_json/?callback=mycallback",
function(data){
$('.result').html(data);
});
</script>
Here's the callback that is returned in my browser:
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开发者_如何学JAVA_city": null}}])
I want to be able to pull pieces out like the pk,fields, ct etc...
I tried replacing $('.result').html(data); with $('.result').html(data.pk); to see if something like that would work but had no success.
Any help would be appreciated.
Thanks!
The data
parameter to your success callback is an object if the response is JSON. Trying to parse it as HTML doesn't make sense:
function(data) {
alert("pk = " + data[0].pk);
}
try $('.result').html(data[0].pk);
jQuery.getJSON()
has JSONP support. This might be what you're looking for.
Use ?callback=?
in the URL instead of ?callback=mycallback
to get it working.
http://api.jquery.com/jQuery.getJSON/
精彩评论