简体   繁体   中英

How to get a json response from yaler

I create an account with yaler, to comunicate with my arduino yun. It works fine, and i'm able to switch on and off my leds. Then i created a web page, with a button that calls an ajax function with GET method to yaler (yaler web server accept REST style on the URL)

$.ajax({
   url: "http://RELAY_DOMAIN.try.yaler.net/arduino/digital/13/1",
   dataType: "json",
   success: function(msg){
      var jsonStr = msg;
    },
   error: function(err){
       alert(err.responseText);
   }

});

This code seem to work fine, infact the led switches off and on, but i expect a json response in success function (msg) like this:

{
"command":"digital",
"pin":13,
"value":1,
"action":"write"
}

But i get an error (error function). I also tried to alert the err.responseText, but it is undefined....

How could i solve the issue? Any suggestions??? Thanks in advance....

If the Web page containing the above Ajax request is served from a different origin, you'll have to work around the same origin policy of your Web browser.

There are two ways to do this (based on http://forum.arduino.cc/index.php?topic=304804 ):

  • CORS , ie adding the header Access-Control-Allow-Origin: * to the Yun Web service
  • JSONP , ie getting the Yun to serve an additional JS function if requested by the Ajax call with a query parameter ?callback=?

CORS can probably be configured in the OpenWRT part of the Yun, while JSONP could be added to the Brige.ino code (which you seem to be using).

I had the same problem. I used JSONP to solve it. JSONP is JSON with padding. Basically means you send the JSON data with a sort of wrapper. Instead of just the data you have to send a Java Script function and this is allowed by the internet.

So instead of your response being :

{"command":"digital","pin":13,"value":0,"action":"write"}

It should be:

showResult({command:"analog",pin:13,value:0,action:"write"});

I changed the yunYaler.ino to do this.

So for the html :

 var url = 'http://try.yaler.net/realy-domain/analog/13/210'; $.ajax({ type: 'GET', url: url, async: false, jsonpCallback: 'showResult', contentType: "application/json", dataType: 'jsonp', success: function(json) { console.dir(json.action); }, error: function(e) { console.log(e.message); } }); }; function showResult(show) { var str = "command = "+show.command;// you can do the others the same way. alert (str); }

My JSON is wrapped with a showResult() so its made JSONP and its the function I called in the callback.

Hope this helps. If CORS worked for you. Could you please put up how it worked here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM