极客工坊

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 18569|回复: 2

客户端读取arduino服务器的json数据

[复制链接]
发表于 2013-6-13 21:20:19 | 显示全部楼层 |阅读模式
大家好,我在arduino上建立一个web服务器,当发送get请求时,返回json数据,但现在是用浏览器可以读取到该json数据,但用jquery在网页里面却读取不到,是怎么回事呢? 我将服务器的代码和客户端的代码贴下来,大家看看。

服务器代码:

    #include <SPI.h>
    #include <Ethernet.h>
    // Enter a MAC address and IP address for your controller below.
    // The IP address will be dependent on your local network:
    byte mac[] = {
    0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    IPAddress ip(192,168,1, 177);
    char cmd[15];
    char param1[15];
    boolean systemArmed = true;
    #define STRING_BUFFER_SIZE 512
    char buffer[STRING_BUFFER_SIZE];
    EthernetServer server(80);
    void setup() {
    Serial.begin(9600);
    // start the Ethernet connection and the server:
    Ethernet.begin(mac, ip);
    server.begin();
    Serial.print("server is at ");
    Serial.println(Ethernet.localIP());
    }
    void send404(EthernetClient client) {
    client.println("HTTP/1.1 404 OK");
    client.println("Content-Type: text/html");
    client.println("Connnection: close");
    client.println();
    client.println("<!DOCTYPE HTML>");
    client.println("<html><body>404</body></html>");
    }
    void sendStatus(EthernetClient client) {
    // Send a standard http response header
    Serial.println("test");
    client.println("HTTP/1.1 200 OK");
    client.println("Content-Type: application/json");
    //client.println("Connnection: close");
    client.println();
    client.println("{");
    // Output the value of each analog input pin
    for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
    int sensorReading = analogRead(analogChannel);
    client.print("\"analog_in_");
    client.print(analogChannel);
    client.print("\": ");
    client.print(sensorReading);
    // if (analogChannel != 5) {
    client.println(",");
    // }
    }
    client.print("\"system_armed\": ");
    client.print( systemArmed );
    client.println("\n}");
    }
    /**
    * Parse the string and return an array which contains all path segments
    */
    char** parse(char* str) {
    char ** messages;
    messages = (char**)malloc(sizeof(char *));
    char *p;
    p = strtok(str, " ");
    unsigned int i = 0;
    while (p != NULL) {
    p = strtok(NULL, "/");
    char *sp;
    boolean last = false;
    sp = strchr(p, ' ');
    if (sp != NULL) {
    *sp++ = '\0';
    last = true;
    }
    messages[i] = p;
    i++;
    if (last) {
    break;
    }
    messages = (char**)realloc(messages, sizeof(char *) * i + 1);
    }
    messages[i] = '\0';
    return messages;
    }
    void armSystem() {
    systemArmed = true;
    }
    void disarmSystem() {
    systemArmed = false;
    }
    void handleCommand(EthernetClient client, char* cmd, char* param) {
      Serial.println("jfasl;jfalskjfalsk");
    if (strcmp(cmd, "status") == 0) {
    Serial.println("status");
    sendStatus(client);
    } else if (strcmp(cmd, "arm") == 0) {
    armSystem();
    sendStatus(client);
    Serial.println("arm");
    } else if (strcmp(cmd, "disarm") == 0) {
    disarmSystem();
    sendStatus(client);
    Serial.println("disarm");
    } else {
    send404(client);
    }
    }
    int countSegments(char* str) {
    int p = 0;
    int count = 0;
    while (str[p] != '\0') {
    if (str[p] == '/') {
    count++;
    }
    p++;
    }
    // We don't want to count the / in 'HTTP/1.1'
    count--;
    return count;
    }
    void loop() {
    // listen for incoming clients
    EthernetClient client = server.available();
    if (client) {
    // an http request ends with a blank line
    Serial.println("in loop");
    boolean currentLineIsBlank = true;
    while (client.connected()) {
    if (client.available()) {
    char c;
    int bufindex = 0; // reset buffer
    buffer[0] = client.read();
    buffer[1] = client.read();
    bufindex = 2;
    // Read the first line to determin the request page
    while (buffer[bufindex-2] != '\r' && buffer[bufindex-1] != '\n') {
      //Serial.println("hahahahah");
      //Serial.println(buffer[0]);
      //Serial.println(buffer[1]);
      
    // read full row and save it in buffer
    c = client.read();
    if (bufindex<STRING_BUFFER_SIZE) {
    buffer[bufindex] = c;
    Serial.println(buffer[bufindex]);
    }
    bufindex++;
    }
    // Clean buffer for next row
    bufindex = 0;
    // Parse the query string
    int nSegments = countSegments(buffer);
    char **pathsegments = parse(buffer);
    int i = 0;
    for(i=0; i<nSegments; i++) {
    Serial.println(pathsegments[i]);
    }
    if (c == '\n' && currentLineIsBlank) {
    handleCommand(client, pathsegments[0], pathsegments[1]);
    break;
    }
    if (c == '\n') {
    currentLineIsBlank = true;
    } else if (c != '\r') {
    currentLineIsBlank = false;
    }
    }
    }
    // Give the web browser time to receive the data
    delay(20);
    // Close the connection:
    client.stop();
    Serial.println("Client disonnected");
    }
    }

客户端代码:

<html>
<head>
<script type="text/javascript" src="jquery-2.0.2.js"></script>
<script type="text/javascript">

//window.setInterval(getData, 3000);

//var oJSON;
var xmlHttp;
function createXMLHttpRequest()
{
    if(window.ActiveXObject)
    {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if(window.XMLHttpRequest)
    {
        xmlHttp = new XMLHttpRequest();
    }
}


function startRequest()
{
    createXMLHttpRequest();
    try
    {
        xmlHttp.onreadystatechange = handleStateChange;
        xmlHttp.open("GET", "http://192.168.1.177/status", true);
        xmlHttp.send(null);
    }
    catch(exception)
    {
        alert("xmlHttp Fail");
    }
}
function handleStateChange()
{  
    if(xmlHttp.readyState == 4)
    {      
        if (xmlHttp.status == 200 || xmlHttp.status == 0)
        {
            var result = xmlHttp.responseText;
            //var json = eval('(' + result + ')');
            alert("result:="+result);
            
            
        }
    }
}

}

</script>
</head>

<body>


<input type="text" name="input" size=100 />
<input type="button" name="clicked" onclick="startRequest()">

</body>

</html>
回复

使用道具 举报

发表于 2013-6-14 10:23:08 | 显示全部楼层
你在浏览器上直接输网址 看看有没有json格式的数据返回来,另外JSON本身就是为jS设计的 jquery下调用极其简单,你的代码我看不懂
回复 支持 反对

使用道具 举报

发表于 2013-10-1 00:39:51 | 显示全部楼层
JSON不能跨域传输,了解下JSONP! http://www.cnblogs.com/chopper/archive/2012/03/24/2403945.html
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

Archiver|联系我们|极客工坊

GMT+8, 2026-6-5 17:42 , Processed in 0.036997 second(s), 19 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表