dongyan6503 2010-07-29 09:54
浏览 53
已采纳

JSON PHP Javascript - 简单的工作示例

HI,

I am using the following code

request.js

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+        "
- "+JSONobject.error[0]+     "
- "+JSONobject.error[1];

    alert(msg);
  }
  catch(ee)
  {
    var errr="Error: "+ee.description;
    alert(errr);
  }
    }
}

The php function I have used here is request.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);

?>

I'm calling this JavaScript function from a HTML page request.html

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

The problem here is I was getting Syntax Error at the line:24

var JSONobject = JSON.parse(JSONtext);

if I was using

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

I was getting " ) Expected Error "

After that I deleted browser cache. Restarted the browser, now the code seems working very fine.

  • 写回答

1条回答 默认 最新

  • dou47278 2010-07-29 11:37
    关注

    You should verify JSON format, then look up there - http://ru.wikipedia.org/wiki/JSON. You can get an idea.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况