I'm having an issue obtaining json from a piec开发者_如何学JAVAe of hardware on a local network.
I can view the json code using this address in a browser:
http://192.168.1.103/device.json
I also saved the resulting text to a file device.json and placed it in the same directory as my test.php file.
This code works:
$.getJSON('device.json',function(data) {
$.each(data.mainunit.sensors, function(i, sensor) {
$("#results").append('<p>'+sensor.name+' = '+sensor.tc+'</p>');
});
This doesn't work: (changing device.json to http://192.168.1.103/device.json)
$.getJSON('http://192.168.1.103/device.json',function(data) {
$.each(data.mainunit.sensors, function(i, sensor) {
$("#results").append('<p>'+sensor.name+' = '+sensor.tc+'</p>');
});
My guess is the code can't view the JSON file at the IP address.
Thanks in advance.
You should wrap your JSON with some callback function. If your device.json
looks like that:
{ "a" : true, "b" : false }
Modify it to be JSONP-compliant:
my_wrapper() { { "a" : true, "b" : false } }
How to request:
$.ajax({
url: "http://192.168.1.103/device.json",
type: "GET",
dataType: "jsonp",
jsonpCallback: "my_wrapper",
success: function(data) {
//Handle data
}
}
Didn't test the code.
Probably a same origin policy violation:
Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
Under "Additional Notes" on this page: http://api.jquery.com/jQuery.getJSON/
Possible solutions:
- Use JSONP as per @floatless suggestion.
- Ask the device manufacturer to add
Access-Control-Allow-Origin: *
header (more about it at MDN). - Proxy requests to your device while adding either JSONP wrapping or the Access-Control-Allow-Origin header.
The last one is that you can do right away.
精彩评论