简体   繁体   中英

Unable to show data. SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

I am passing a variable from an AJAX function to a PHP page. AJAX function is called on a button click & a value is passed as parameter. AJAX function passes this variable to a php page to_php_page.php from where a HTTP GET request is made to the server. This variable is passed as the parameter. We get many city datas as response. The corresponding response is stored in different arrays & is encoded as JSON & passed back to the AJAX function. All these datas are shown at once.

But, Instead of getting the response, I am getting an error.

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

AJAX Function

<script>

    function get_data(n)
    {
        if(window.XMLHttpRequest)
        {
            xmlhttp=new XMLHttpRequest();
        }
        else
        {
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function() //callback fn
        {
            if(xmlhttp.readyState==4 && xmlhttp.status==200)
            {
                var jsonStr = JSON.parse(xmlhttp.responseText);
                var count_array=parseInt(jsonStr.count);
                var la=jsonStr.la;
                var ny=jsonStr.ny;
                var sj=jsonStr.sj;
                var lv=jsonStr.lv;
                var ut=jsonStr.ut;
                var dc=jsonStr.dc;
                var miami=jsonStr.miami;
                var columbus=jsonStr.columbus;
                var kc=jsonStr.kc;
                var ch=jsonStr.ch;

                for (i = 0; i < count_array; i++)
                {
                    (function()
                    {
                        alert(la);
                        alert(ny);
                        alert(sj);
                        alert(lv);
                        alert(ut);
                        alert(dc);
                        alert(miami);
                        alert(columbus);
                        alert(kc);
                        alert(ch);
                    })();
                }

            }
        }
        xmlhttp.open("GET","to_php_page.php?namee="+n,true);
        xmlhttp.send();
    }
</script>

to_php_page.php

<?php
$namee_value=$_GET["namee"];
// Above variable is passed as argument with the url to obtain the response.

$url="server_url?nam=".$namee_value;
$jsondata= httpGet($url);
$details_array = json_decode($jsondata, true);
$count=count($details_array['country']);

function httpGet($url)
{
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_HEADER, false);
    $output=curl_exec($ch);
    curl_close($ch);
    return $output;
}

//for storing los angeles details
$la=array();
for($i=0;$i<$count;$i++)
{
    $la[$i]= $details_array['country'][$i]['los_angeles'];
}

//for storing new york details
$ny=array();
for($i=0;$i<$count;$i++)
{
    $ny[$i]= $details_array['country'][$i]['new_york'];
}

//for storing san jose details
$sj=array();
for($i=0;$i<$count;$i++)
{
    $sj[$i]= $details_array['country'][$i]['san_jose'];
}

//for storing las vegas details
$lv=array();
for($i=0;$i<$count;$i++)
{
    $lv[$i]= $details_array['country'][$i]['las_vegas'];
}

//for storing utah details
$ut=array();
for($i=0;$i<$count;$i++)
{
    $ut[$i]= $details_array['country'][$i]['utah'];
}

//for storing washington details
$dc=array();
for($i=0;$i<$count;$i++)
{
    $dc[$i]= $details_array['country'][$i]['washington_dc'];
}

//for storing miami details
$miami=array();
for($i=0;$i<$count;$i++)
{
    $miami[$i]= $details_array['country'][$i]['miami'];
}

//for storing columbus details
$columbus=array();
for($i=0;$i<$count;$i++)
{
    $columbus[$i]= $details_array['country'][$i]['columbus'];
}

//for storing kansas city details
$kc=array();
for($i=0;$i<$count;$i++)
{
    $kc[$i]= $details_array['country'][$i]['kansas_city'];
}

//for storing chicago details
$ch=array();
for($i=0;$i<$count;$i++)
{
    $ch[$i]= $details_array['country'][$i]['chicago'];
}

$what_the_array = array(
    'count' => $count,
    'la' => $la,
    'ny' => $ny,
    'sj'=> $sj,
    'lv'=>$lv,
    'ut'=>$ut,
    'dc'=>$dc,
    'miami'=>$miami,
    'columbus'=>$columbus,
    'kc'=>$kc,
    'ch'=>$ch
);

echo json_encode($what_the_array);
?>

UPDATE:

JSON to be parsed:

{
    "country":
        [
            {
                "los_angeles": "value1",
                "new_york": "value2",
                "san_jose": "value3",
                "las_vegas": "value4",
                "utah": "value5",
                "washington_dc": "value6",
                "miami": "value7",
                "columbus": "value8",
                "kansas_city": "value9",
                "chicago": "value10"
            }
        ]
}

NB: Is there an alternative for the AJAX function I have used?? I mean, another AJAX function. I use this all time. I am looking for a much better AJAX function.

You may have two possible problem sources:

1) Content-Type. Specify content type and charset just before sending out JSON from PHP:

Header('Content-Type: application/json;charset=utf8');

(and ensure content is UTF8 encoded).

2) I have recently experienced your same problem. I'm 100% sure the JSON was correct (checked with jsonlint from data lifted off the wire with tcpdump) and the same code had worked up to the day before. The bug was not reproducible in Chrome. It also went unexplicably away after upgrading Firefox and clearing the cache, but it never presented itself on a still non-updated Firefox on another PC. In some cases I noticed that both Firefox and Chrome appear to request a JSON packet but process an earlier version from the cache, but was not able to reproduce the phenomenon in any predictable way. I do know though that to prevent it it is sufficient to add a non-repeating element to the query:

xmlhttp.open("GET","to_php_page.php?namee="+n + "&ts=" + Date.now(), true);

This effectively disables caching for that request, so for large JSON resources that change rarely, it isn't really a good thing to do.

Other possibilities

You ought to verify whether the cUrl request PHP side does return properly. You might have an error, possibly a cUrl warning of some kind issued by httpGet.

Try opening the URL directly in the browser. If you see something like

PHP Warning: curl_exec: ... { (JSON) }

well, that of course is not JSON and JSON.parse() will complain that the "P" in "PHP Warning" is indeed an unexpected character.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM