代码之家  ›  专栏  ›  技术社区  ›  Vinothkumar Arputharaj

json php javascript-简单的工作示例

  •  1
  • Vinothkumar Arputharaj  · 技术社区  · 15 年前

    你好,

    我使用以下代码

    请求程序

    var request;
    function runAjax(JSONstring)
    {
    
        // function returns "AJAX" object, depending on web browser
        // this is not native JS function!
        request = new XMLHttpRequest();
    
        request.open("GET", "request.php?json="+JSONstring, true);
        request.onreadystatechange = sendData;
        alert('called');
        request.send(null);
    }
    
    function sendData()
    {
        // if request object received response
        if(request.readyState == 4)
        {
        // parser.php response
        var JSONtext = request.responseText;
        // convert received string to JavaScript object
      try
      {
      //var JSONobject = eval('(' + JSONtext + ')');
        var JSONobject = JSON.parse(JSONtext);
      }
      catch(e)
      {
        var err="Error: "+e.description;
        alert(err);
      }
     alert('1');
        // notice how variables are used
      try {
    
        var msg = "Number of errors: "+JSONobject.errorsNum+        "\n- "+JSONobject.error[0]+     "\n- "+JSONobject.error[1];
    
        alert(msg);
      }
      catch(ee)
      {
        var errr="Error: "+ee.description;
        alert(errr);
      }
        }
    }
    

    我在这里使用的PHP函数是 请求程序

    <?php
    
    // decode JSON string to PHP object
    $decoded = json_decode($_GET['json']);
    
    // do something with data here
     echo "Decoded string - ". $decoded;
    // create response object
    $json = array();
    $json['errorsNum'] = 2;
    $json['error'] = array();
    $json['error'][] = 'Wrong email!';
    $json['error'][] = 'Wrong hobby!';
    
    // encode array $json to JSON string
    $encoded = json_encode($json);
    
    
    // send response back to index.html
    // and end script execution
    die($encoded);
    
    ?>
    

    我从HTML页面调用这个javascript函数 请求HTML

    <html>
    <head>
    <script src="request.js">
    </script>
    </head>
    <body>
    <a href="Javascript:runAjax('vinoth')">call</a><br>
    </body>
    </html>
    

    这里的问题是我得到了 语法错误 在线:24

    var JSONobject = JSON.parse(JSONtext);
    

    如果我在用

    var JSONobject = eval('(' + JSONtext + ')');
    

    我得到 “)预期错误”

    之后我删除了浏览器缓存。重新启动浏览器,现在代码看起来工作得很好。

    1 回复  |  直到 11 年前
        1
  •  0
  •   monsur    12 年前

    您应该验证JSON格式,然后在那里查找- http://ru.wikipedia.org/wiki/JSON . 你可以得到一个主意。

    推荐文章