HI,
我正在使用以下代码
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+ "\n- "+JSONobject.error[0]+ "\n- "+JSONobject.error[1];
alert(msg);
}
catch(ee)
{
var errr="Error: "+ee.description;
alert(errr);
}
}
}
我在这里使用的php函数是 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);
?>
我从HTML页面 request.html
调用此JavaScript函数<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 + ')');
我正在 “)预期错误”
之后我删除了浏览器缓存。重新启动浏览器,现在代码似乎工作正常。