格式不正确的JSON通过ajax传递

时间:2013-06-03 19:01:24

标签: php javascript ajax json

嘿,伙计们在这里遇到了令人沮丧的错误。我有一个JSON格式的数组,我通过AJAX从PHP脚本传递到javascript,虽然我通过验证器运行输出的JSON,但javascript在jQuery.parseJSON()步骤继续失败,给我一个错误。<登记/> 错误为Uncaught Syntax Error unexpected token <

任何人都知道问题可能是什么?

<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
function showHint(str)
{
  var xmlhttp;
  if (str.length==0)
  { 
    document.getElementById("txtHint").innerHTML="";
    return;
  }
  if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }
  else
  {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function()
  {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
      var data=xmlhttp.responseText;
      document.getElementById("txtHint").innerHTML=data;
      var jsonData = jQuery.parseJSON('{"name":"John"}');
      alert("Got here Second!");
      document.getElementById("hints").innerHTML = jsonData[0][1];
      alert("Probably failed...");
    }
  }
  xmlhttp.open("GET","getSuggestion.php?q="+str,true);
  xmlhttp.send();
}
</script>
</head>
<body>

<h3>Start typing a name in the input field below:</h3>
<form action=""> 
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)" />
</form>
<p>Suggestions: <span id="txtHint"></span></p> 
<p>Actual Hints: <span id="hints"></span></p> 

</body>
</html>

PHP:

<?php
header('Content-type: application/json');
function getHint($companyName)
{
    try
    {
        $first = getJson($companyName);
        $temp = strpos($first, "(") + 1;
        $second = substr($first, $temp, strlen($first) - $temp - 1);//this line produces valid JSON
        $json = json_decode($second,true);
    }
    catch(Exception $e)
    {
        echo "caught Exception " , $e->getMessage();
    }
    return $json;
}
function getJson($companyName)
{
    $partial = urlencode($companyName);
    $searchURL = "http://d.yimg.com/autoc.finance.yahoo.com/autoc?query=" . $partial . "&callback=YAHOO.Finance.SymbolSuggest.ssCallback";
    $filesize = 4000;
    $handle = fopen($searchURL,"r");
    $jsonData = fread($handle,$filesize);
    fclose($handle);
    return $jsonData;
}
$q=$_GET["q"];
$roof = getHint($q);
//TODO: kill if no suggestion
$collection = $roof[ResultSet][Result];
echo json_encode($collection);
?>

示例JSON

[{"symbol":"A","name":"Agilent Technologies Inc.","exch":"NYQ","type":"S","exchDisp":"NYSE","typeDisp":"Equity"},{"symbol":"^DJI","name":"Dow Jones Industrial Average","exch":"DJI","type":"I","typeDisp":"Index"},{"symbol":"AAPL","name":"Apple Inc.","exch":"NMS","type":"S","exchDisp":"NASDAQ","typeDisp":"Equity"},{"symbol":"BAC","name":"Bank of America Corporation","exch":"NYQ","type":"S","exchDisp":"NYSE","typeDisp":"Equity"},{"symbol":"FNMA","name":"Federal National Mortgage Association","exch":"OBB","type":"S","exchDisp":"OTC BB","typeDisp":"Equity"},{"symbol":"T","name":"AT&T, Inc.","exch":"NYQ","type":"S","exchDisp":"NYSE","typeDisp":"Equity"},{"symbol":"AFFY","name":"Affymax, Inc.","exch":"NMS","type":"S","exchDisp":"NASDAQ","typeDisp":"Equity"},{"symbol":"AMZN","name":"Amazon.com Inc.","exch":"NMS","type":"S","exchDisp":"NASDAQ","typeDisp":"Equity"},{"symbol":"DIA","name":"SPDR Dow Jones Industrial Average","exch":"PCX","type":"E","typeDisp":"ETF"},{"symbol":"AUDUSD=X","name":"AUD\/USD","exch":"CCY","type":"C","typeDisp":"Currency"}] 

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您无需解析JSON代码。它已经有效了:

See this JSFiddle

通过这种方式:

的Javascript

for(var i in myArray)
{
  content += "<div class=\"symbol\">";
  content += "Symbol = "+myArray[i].symbol +"<br />";
  content += "Name = "+myArray[i].name+"<br />";
  content += "exch = "+myArray[i].exch+"<br />";
  content += "Type = "+myArray[i].type+"<br />";
  content += "</div>";
}