Domanda

What is the proper way to encode/decode data with JSON using PHP and Javascript

My PHP is simple:

session_start();
header('Content-type: application/json');
echo json_encode($_SESSION['orl']);

Simple name value pairs in text, no objects or anything.

My JavaScript is

function checkForSeshStuff(){
    window.alert("check sesh called");
    GM_xmlhttpRequest({
        method: "GET",
        url: "http://internal.example.com/orl_get_sesh.php",
        onload: function(response) {
            window.alert(response.responseText);
            var obj = JSON.parse(response.responseText);
            window.alert(obj.count);
            if(obj.count > 1){
                document.getElementById('ajaxSeshStat').innerHTML = "<input type='button' onclick='loadLastSesh();' value='Populate "+obj.count+" Fields' />";
                document.getElementById('ajaxSeshStat').style.display = "block";
            }
        }
    });
}

I have a bunch of alerts for debugging, the third one which alerts the JSON count alerts "undefined" every time.

Am I using the proper mime type in my PHP? Am I parsing correctly in my JS? What's wrong?

EDIT Here's the string of JSON data generated by PHP

{"BodyContent_ctl00_ctl00_chRead":"on","BodyContent_ctl00_ctl00_txtOfferCode":"xc","BodyContent_ctl00_ctl00_txtFirstName1":"cx","BodyContent_ctl00_ctl00_txtCity1":"Beverly Hills","BodyContent_ctl00_ctl00_txtZip1":"90210","BodyContent_ctl00_ctl00_txtMonthlyIncome1":"0","BodyContent_ctl00_ctl00_txtOtherIncome1":"0","BodyContent_ctl00_ctl00_chbCoBorrowerContactInformation":"on","BodyContent_ctl00_ctl00_txtMonthlyIncome2":"0","BodyContent_ctl00_ctl00_txtOtherIncome2":"0"}

È stato utile?

Soluzione

Does your session have a count element in the array? It doesn't look like it.

Have you tried:

alert(obj.BodyContent_ctl00_ctl00_txtZip1)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top